无法使Symfony验证工作

时间:2012-09-30 08:23:09

标签: php symfony validation

我正在尝试为我的注册表单添加一些验证,但我无法让它工作,到目前为止我已经添加了我的用户实体

片段。

class User {

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
   protected $userid;

/**
 * @ORM\Column(type="string", length=30)
 */
 protected $username;

为此我已经将validation.yml添加到我的包中。

# src/Blomster/UserBundle/Resources/config/validation.yml

Blomster/UserBundle/Entity/User:
    properties:
        username:
            - NotBlank: ~
            - MinLength: { limit: 3, message: "Username is too short." }
            - MaxLength: { limit: 15, message: "Username is too long." }

使用$ form-> isValid()始终返回true,所以我尝试var_dump我的表单

      'validation_groups' => null
      'validation_constraint' => null
      'constraints' => 
        array (size=0)
          ...

表单本身运行良好,它在提交时添加到我的数据库中,我是否需要以某种方式向表单添加约束?

添加了UserType.php

class UserType extends AbstractType {

  public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('username', null, array('label' => 'Username'));
    $builder->add('email', 'email', array('label' => 'Email'));
    $builder->add('password', 'repeated', array(
        'type' => 'password',
        'required' => true,
        'first_options' => array('label' => 'Password'),
        'second_options' => array('label' => 'Repeat password'),
      ));
  }

  public function getDefaultOptions(array $options) {
    return array('data_class' => 'Blomster\UserBundle\Entity\User');
  }

  public function getName() {
    return 'user';
  }
}

1 个答案:

答案 0 :(得分:1)

您需要使用长度限制:

        - MinLength: { limit: 3 }
        - MaxLength: { limit: 15 }

here是文档。

实际上:您需要指定限制,因为您还可以设置其他选项,例如消息等。