3

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.

Bananaapple
  • 2,984
  • 2
  • 25
  • 38
  • Have you tried adding the constraint to the form instead of/in addition to the entity assertion? – dbrumann Feb 19 '21 at 16:11
  • 2
    @dbrumann It will not work, it's due to a `TransformationFailedException` triggered by the `RepeatedType` transformer. This add the error before validating the RepeatedType's children. It's by design and I think there's no solution to this issue. – jona303 Feb 19 '21 at 16:24
  • 1
    Why don't you add the EmailType to the RepeatedType? It's only a html5 check but the syntax will be check first. – SubCore Feb 19 '21 at 18:47

1 Answers1

0

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'
            ])
        ]
    ]);
Pavol Velky
  • 770
  • 3
  • 9