Symfony 2重复字段验证重复消息

时间:2014-05-14 08:32:27

标签: php forms validation symfony error-handling

我在symfony 2中有这个注册表格。 密码字段是重复的'类型:

$builder
...
->add('password', 'repeated', array( 
                    'type' => 'password',
                    'invalid_message' => 'The passwords must match.',
                    'required' => true,
                    'first_options'  => array('label' => 'Password:'),
                    'second_options' => array('label' => 'Repeat Password:'),
                    'constraints' => array(
                            new Assert\NotBlank(array('message' => 'Password should not be blank.')),
                            new Assert\Length(array(
                                    'min' => 8,
                                    'max' => 40,
                                    'minMessage' => "Password must be at least {{ limit }} characters long.",
                                    'maxMessage' => "Password cannot be longer than {{ limit }} characters.",
        )),
    )
))
...

在twig模板中,仅使用form.password是不够的,因为不会显示错误消息。我必须使用form.password.first。

{% if not form.vars.valid %}
...
    {{ form_errors(form.password.first) }}
...
{% endif  %}

结果是:

The password must be at least 8 characters long.  <-- The default error message
Password must be at least 8 characters long.      <-- Mine

如果我没有设置minMessage或maxMessage,结果是:

The password must be at least 8 characters long.  
This value is too short. It should have 8 characters or more. <-- Default minMessage message

如何让它只显示一条错误消息?当然,我可以拦截控制器中的表单错误并在那里操作它,但我想要一个更好的解决方案。

1 个答案:

答案 0 :(得分:0)

Mb 已经晚了,但我仍然没有看到关于同一问题的太多信息。在 symfony 4.4 这对我有用

$form->add('password', RepeatedType::class, [
    'type' => PasswordType::class,
    'required' => true,
    'invalid_message' => 'your message',
    'first_options' => ['label' => 'Password'],
    'second_options' => ['label' => 'Repeat Password'],
    'options' => ['error_bubbling' => true],
    //'error_bubbling' => false, default
    ...
]);