How to control Symfony's RepeatedType validation sequence

Viewed 208

I am using Symfony's RepeatedType for an email address on a registration form.

$builder->add(
    'email',
    RepeatedType::class,
    [
        'invalid_message' => 'Confirm your email address',
    ]
);

I am also adding constraints to the property declaration itself:

/**
 * @var string|null
 *
 * @Assert\NotBlank
 * @Assert\Email(message="You must enter a valid email address")
 */
private ?string $email = null; 

The problem is that Symfony runs the RepeatedType validation before it runs the property specific ones.

In other words, if you enter an incorrect email address it will first ensure that you entered that incorrect email address twice before telling you it's wrong.

Same applies to my password by the way - it asserts that you re-entered it correctly before telling you password strength requirements weren't met.

I know that I can control the sequence of validation groups but since RepeatedType isn't applied to the model itself I am unsure how to achieve this.

1 Answers

If you want to customize this behavior, you can check if email addresses are same with constraint on non mapped property:

use Symfony\Component\Validator\Constraints\EqualTo;

$builder->add('email', EmailType::class)
    ->add('email_repeat', EmailType::class, [
        'mapped' => false,
        'constraints' => [
            new EqualTo([
                'propertyPath' => 'email'
            ])
        ]
    ]);
Related