Home > Software design >  Symfony 5 - Regex Validator which was working now doesn't work
Symfony 5 - Regex Validator which was working now doesn't work

Time:10-15

So i have an Entity with @Assert/Regex

/**
     * @var string
     *
     * @ORM\Column(name="firstname", type="string", length=30, nullable=false, options={"comment"="input#text&[A-Za-z \-\'àâäçéèêëîïôöùûüÿæœÀÂÄÇÉÈÊËÎÏÔÖÙÛÜŸÆŒ]{2,30}@Prénom"})
     * @Assert\NotBlank (
     *     message="Le champs [prénom] ne peut être vide",
     *     groups={"registration"}
     * )
     * @Assert\Regex (
     *     pattern="/^[A-Za-z \-\'àâäçéèêëîïôöùûüÿæœÀÂÄÇÉÈÊËÎÏÔÖÙÛÜŸÆŒ]{2,30}$/",
     *     message="Champs prénom : La saisie est invalide (min: 2, max: 30)")
     */
    private $firstname;

    /**
     * @var string
     *
     * @ORM\Column(name="lastname", type="string", length=30, nullable=false, options={"comment"="input#text&[A-Za-z \-\'àâäçéèêëîïôöùûüÿæœÀÂÄÇÉÈÊËÎÏÔÖÙÛÜŸÆŒ]{2,30}@Nom"})
     * @Assert\NotBlank (
     *     message="Le champs [nom] ne peut être vide",
     *     groups={"registration"}
     * )
     * @Assert\Regex (
     *     pattern="/^[A-Za-z \-\'àâäçéèêëîïôöùûüÿæœÀÂÄÇÉÈÊËÎÏÔÖÙÛÜŸÆŒ]{2,30}$/",
     *     message="Champs nom : La saisie est invalide (min: 2, max: 30)")
     */
    private $lastname;

And i have my controller like so (I purposely removed most of my code to keep it lisible)

public function register(ValidatorInterface $validator, EntityManagerInterface $emi): Response
{
    $newUsers = new Users();
            
    // Setting the values
    $newUsers
        ->setFirstname($request->get('firstname'))
        ->setLastname($request->get('lastname'));

    $errorsUsers = $validator->validate($newUsers, null, ['registration']);
    foreach ($errorsUsers as $v){
        $msgErrors .= "\n- " . $v->getMessage() . ".";
    }
}

Before everything worked perfectly. And now the Assert\NotBlank is still working but the Assert\Regex is not. It's like, it doesn't even compare it.

I tried :

  • php bin/console debug:validator 'App\Entity\Users' (all seems fine)
  • composer dump-autoload (nothing change)
  • Put instead in my regex simple parttern like "/\d/" (even that when i type 'Toto' it doesn't trigger and return a violation)

I don't know why it's not working anymore and thats why i hate symfony for this cause it doesn't even give an error or message to start with.

If someone has encountered this problem and has a solution to give, please let me know.

Thanks in advance.

CodePudding user response:

Ok so the problem was the fact that i didn't put the groups in the regex too.

so for each Assert that you add on a var, you need to specify the groups.

I didn't think of it, because in the doc it says that if you don't specify groups it means that it apply for everything. Obviously it is not.

Thanks doc.

  • Related