Symfony - Restrict registration from specific domain

北城以北 提交于 2019-12-12 10:19:50

问题


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


回答1:


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



回答2:


You can use Regex constraint to test email address for several email domains. In other case you will have to create your own constraint.



来源:https://stackoverflow.com/questions/36451825/symfony-restrict-registration-from-specific-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!