Symfony 表单长度约束覆盖 NotBlank 约束

Symfony forms Length constraint overrides NotBlank constraint

因此,在我的表单中,我有一个用于插入密码的字段。在 formbuilder 的字段上,我添加了 2 个约束;一种用于字段是否为空,另一种用于密码太短。

new NotBlank([
    'message' => 'reset.password.error.enterpassword',
]),
new Length([
    'min' => 6,
    'minMessage' => 'reset.password.error.passwordtooshort',
    // max length allowed by Symfony for security reasons
    'max' => 4096,
]),

但是,当我将密码字段留空时,它会使用长度约束(我有点理解,因为长度为 0 的密码小于 6),但它不应该使用 NotBlank 约束吗,因为它是定义?

我也试过把它放在长度约束之后,但还是不行。

Length 验证器的行为在最近的 symfony 版本中发生了变化。

以前它匹配空输入。

选项allowEmptyString 控制是否允许空字符串。

它默认为 false 而旧的 symfony 版本默认为 true

请参阅文档 Length#allowemptystring

allowEmptyString 设置为 true 以解决您的问题:

new Length([
    'allowEmptyString' => true,
    'min' => 6,
    'minMessage' => 'reset.password.error.passwordtooshort',
    // max length allowed by Symfony for security reasons
    'max' => 4096,
]),
new NotBlank([
    'message' => 'reset.password.error.enterpassword',
]),