【问题标题】:Symfony Validation Constraint Assert\Date() is accepting empty stringSymfony 验证约束 Assert\Date() 正在接受空字符串
【发布时间】:2018-03-02 20:24:51
【问题描述】:

在一个实体类中,我定义了一个类似的属性

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 约束虽然有效。 我想我在日期约束使用中遗漏了一些特定的东西?

【问题讨论】:

  • 每个字段可以有多个约束 - 在注释中添加新行 - * @Assert\NotBlank()
  • @AlisterBulman 谢谢。这有帮助。 Janney Botis 在下面回答得更完整。

标签: symfony validation constraints symfony-3.3 symfony3.x


【解决方案1】:

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

要使字段中的空值无效,您应该按照正确的说明添加 NotBlank 约束

这是行:code for DateValidator

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

参考文献:

  1. Similar answer
  2. Github issue
  3. Explanation

【讨论】:

  • 谢谢。明白了 :-) 除了小问题:有没有办法为我可以为 Assert 定义的消息定义一个 translation_domain?
  • 好问题,不幸的是我不知道该怎么做。
猜你喜欢
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 2012-11-13
  • 2012-08-17
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多