Symfony2表单不验证电子邮件和必需的约束

时间:2014-03-08 16:07:26

标签: php forms symfony constraints symfony-forms

我使用Symfony2创建了这样的表单:

class UsuarioRegistroType extends AbstractType {

  public function BuildForm(FormBuilderInterface $builder, array $options) {

    $builder->add('email', 'email', array('label' => 'E-mail',  'required' => true))
....

表单工作正常,但如果我写的东西像电子邮件:asdf(不是电子邮件地址),我从来没有得到与此问题相关的错误。另外,如果我没有写任何内容,我的required constraint没有任何错误。

对这个问题有什么想法吗? 谢谢:))

2 个答案:

答案 0 :(得分:3)

必填项不验证任何内容。它只是在窗体视图上添加字段所需的类。这是验证它的html5。

尝试在UsuarioRegistroType类上添加它:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $collectionConstraint = new Collection(array(
        'email' => array(
            new NotBlank(array('message' => 'Email should not be blank.')),
            new Email(array('message' => 'Invalid email address.'))
        )
    ));

    $resolver->setDefaults(array(
        'constraints' => $collectionConstraint
    ));
}

不要忘记使用声明:

使用Symfony \ Component \ OptionsResolver \ OptionsResolverInterface;

使用Symfony \ Component \ Validator \ Constraints \ Email;

使用Symfony \ Component \ Validator \ Constraints \ NotBlank;

使用Symfony \ Component \ Validator \ Constraints \ Collection;

答案 1 :(得分:0)

您刚刚使用过HTML5验证,很多barowser都不支持此功能。有了这个旧版本的不同着名浏览器也不支持HTML5验证。

我认为您应该使用注释来从服务器端进行验证。我想你知道注释,你可以在你的Entity类中使用它。在您的enity类属性中,您可以使用symfony2中的注释来定义所需的验证规则。

示例:

use Symfony\Component\Validator\Constraints as Assert;

class Author
 {
     /**
      * @Assert\Email(
      *     message = "The email '{{ value }}' is not a valid email.",
      *     checkMX = true
      * )
      */
      protected $email;
 }

来自Symfony2官方文档的有用链接:Symfony2 Validation