Symfony - 限制来自特定域的注册

Symfony - Restrict registration from specific domain

我正在制作一个注册表单,我需要在其中验证电子邮件 ID,如果电子邮件域不属于特定域,那么这个人应该无法注册,所以我的问题是默认情况下使用 symfony有这个我可以打开的验证选项还是我需要创建自定义验证?

例如,我只希望人们在电子邮件 ID 具有 yahoo.com

时进行注册

您可以使用 Regex constraint 来测试多个电子邮件域的电子邮件地址。在其他情况下,您将必须创建自己的约束。

不,symfony2 中没有用于检查域电子邮件的内置功能。但是你可以添加它。你能做的是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();
        }
    }
}

之后你就可以使用新的验证器了:

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;

万一有人需要在 .yml 文件中添加验证,您可以按此操作。

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