Symfony - 限制从特定域注册 [英] Symfony - Restrict registration from specific domain
问题描述
我正在处理一个注册表单,我需要对电子邮件 ID 进行验证,如果电子邮件域不属于特定域,那么人们应该无法注册,所以我的问题是 symfony 默认情况下是否有这个我可以打开验证选项还是需要创建自定义验证?
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?
例如,我只希望人们在电子邮件 ID 具有 yahoo.com
For example I only want people to register if the email id has yahoo.com
推荐答案
不,symfony2 中没有用于检查域电子邮件的内置功能.但是你可以添加它.您可以做的是创建自定义约束.
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;
如果有人需要在 .yml
文件中添加验证,您可以这样做.
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
这篇关于Symfony - 限制从特定域注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!