在一个实体类中,我定义了一个属性
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约束起作用。 我想我缺少某些特定的日期约束用法?
In an Entity class I defined a property like
use Symfony\Component\Validator\Constraints as Assert; class MyEntity { ... /** * @Assert\Date() */ protected $date_of_birth; ... }In the FormType class I use the property:
$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' ), ) ) ;In the template I output the form suppressing browser side validation:
... {{ 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) }} ...Unfortunately it doesn't really matter what I type into the date field. I can leave it empty - it still is OK for the validator. The NotBlank Constraint works though. I suppose I am missing something specific in the Date Constraint usage?
最满意答案
这是预期的行为。 您不会错过任何内容,Date约束的定义中没有选项可以使该字段中的空值无效。
为了使字段中的空值无效,您应该添加NotBlank约束 ,正如您正确说明的那样。
以下是DateValidator的代码 :
例如,对于大多数其他验证器,这是相同的,例如。 即使min> 0, LengthValidator也会验证空字符串。
参考文献:
类似的答案 Github问题 说明This is the expected behaviour. You are not missing anything, there is no option in the definition of the Date constraint to invalidate for empty value in the field.
To invalidate for empty value in the field, you should add the NotBlank Constraint, as you correctly state.
Here is the line: code for DateValidator
For example this is the same for most other validators, eg. LengthValidator will validate for empty string, even if min is >0.
References:
Similar answer Github issue Explanation更多推荐
发布评论