phpformsvalidationsymfonyemail

Symfony how to validate an EmailType by not allowing emails without an ending dot something


Currently the EmailType of Symfony allows any email like:

"whatever@domain"

So there is no validation against the domain of the email

what is the best way to make it accepts only email like:

"whatever@domain.something"

so that the domain should contain at least one dot.

Since it should be a common issue, I was wondering if there's already a built-in way to accomplish it.


Solution

  • Use Email constraint to validate email values correctly:

    use Symfony\Component\Validator\Constraints as Assert;
    
    class User 
    {
        /**
         * @var string
         *
         * @Assert\Email()
         */
        private $email;
    }
    

    On submit the form the EmailValidator checks whether this '/^.+\@\S+\.\S+$/' pattern is valid or not, and throws a violation constraint if not.