Search code examples
phpsymfonysymfony-validator

Symfony - Restrict registration from specific domain


I am working on a registration form where I need to put a validation on email id, if the email domain does not belong to a specific domain then person should not be able to register so my question is does symfony by default has this validation option which I can turn on or i need to create a custom validation?

For example I only want people to register if the email id has yahoo.com


Solution

  • No, there's not a build-in feature in symfony2 for check domain email. But you can add it. What you can do is creating a custom constraint.

    namespace AppBundle\Validator\Constraints;
    
    use Symfony\Component\Validator\Constraint;
    
    /**
     * @Annotation
     */
    class EmailDomain extends Constraint
    {
        public $domains;
        public $message = 'The email "%email%" has not a valid domain.';
    }
    


    namespace AppBundle\Validator\Constraints;
    
    use Symfony\Component\Validator\Constraint;
    use Symfony\Component\Validator\ConstraintValidator;
    
    class EmailDomainValidator extends ConstraintValidator
    {
        public function validate($value, Constraint $constraint)
        {
            $explodedEmail = explode('@', $value);
            $domain = array_pop($explodedEmail);
    
            if (!in_array($domain, $constraint->domains)) {
                $this->context->buildViolation($constraint->message)
                     ->setParameter('%email%', $value)
                     ->addViolation();
            }
        }
    }
    

    After that you can use the new validator:

    use Symfony\Component\Validator\Constraints as Assert;
    use AppBundle\Validator\Constraints as CustomAssert;
    
    class MyEntity
    {
        /**
         * @Assert\Email()
         * @CustomAssert\EmailDomain(domains = {"yahoo.com", "gmail.com"})
         */
        protected $email;
    

    In case someone needs to add the validation inside the .yml file here is how you can do it.

        - AppBundle\Validator\Constraints\EmailDomain:
            domains:
                - yahoo.com