Home > other >  Regex in Symfony 6
Regex in Symfony 6

Time:08-26

The following regex doesn't work in Symfony Sonata form:

$form->add('licensePlate', TextType::class, [
   'constraints' => new Assert\Regex([
       'pattern' => '/[A-Z]{2}-[0-9]{3}-[A-Z]{2}/',
       'match' => false,
       'message' => 'The license plate must be in the format AA-123-BB',
   ])
]);

whereas in regex101 it does.

I wonder if I have to add something else for Symfony.

CodePudding user response:

You need to

  • Change match value from false to true
  • Use ^ and \z anchors to the regex pattern so as to match the whole string with this pattern.

So you can use

$form->add('licensePlate', TextType::class, [
   'constraints' => new Assert\Regex([
       'pattern' => '/^[A-Z]{2}-[0-9]{3}-[A-Z]{2}\z/',
       'match' => true,
       'message' => 'The license plate must be in the format AA-123-BB',
   ])
]);
  • Related