Symfony验证约束Assert\Date()接受空字符串

Symfony验证约束Assert\Date()接受空字符串,symfony,validation,constraints,symfony-3.3,symfony3.x,Symfony,Validation,Constraints,Symfony 3.3,Symfony3.x,在实体类中,我定义了如下属性 use Symfony\Component\Validator\Constraints as Assert; class MyEntity { ... /** * @Assert\Date() */ protected $date_of_birth; ... } 在FormType类中,我使用以下属性: $builder ->add('date_of_birth', DateT

在实体类中,我定义了如下属性

use Symfony\Component\Validator\Constraints as Assert;

class MyEntity
{
    ...

    /**
     * @Assert\Date()
     */
    protected $date_of_birth;

    ...
}
在FormType类中,我使用以下属性:

$builder
    ->add('date_of_birth',
        DateType::class,
        array(
            'label' => 'Birthday',
            'required' => true,
            'translation_domain' => 'messages',
            'widget' => 'single_text',
            'html5' => false,
            'data' => null,
            'format' => $this->container->getParameter('date.format.icu'),
            'attr' => array( 'class' => 'js-bootstrap-datepicker', 'placeholder' => 'DD.MM.YYYY' ),
        )
    )
;
在模板中,我输出表单抑制浏览器端验证:

...
{{ form_start(form_a, {'attr': {'novalidate': 'novalidate'}}) }}
...
{{ form_label(form_a.date_of_birth) }}*
{{ form_errors(form_a.date_of_birth) }}
{{ form_widget(form_a.date_of_birth) }}
...
不幸的是,我在日期字段中键入什么并不重要。我可以将其保留为空-对于验证器来说仍然可以。 但NotBlank约束仍然有效。
我想我在日期约束用法中遗漏了一些特定的内容?

这是预期的行为。 您没有遗漏任何内容,在日期约束的定义中,没有选项可使字段中的空值无效

若要使字段中的空值无效,应添加NotBlank约束,因为您正确地声明了该约束

这是一句话:

例如,对于大多数其他验证器,这是相同的,例如,将验证空字符串,即使min>0

参考资料:


每个字段可以有多个约束-在注释中添加新行-*@Assert\NotBlank@AlisterBulman谢谢这很有帮助。Janney Botis在下面的回答更完整一些。谢谢。明白了:-撇开小问题不谈:有没有办法为消息定义一个翻译域,我可以为断言定义这个域?好问题,不幸的是我不知道如何定义。