Symfony2-如何在控制器中验证电子邮件地址 [英] Symfony2 - How to validate an email address in a controller
问题描述
symfony中有一个电子邮件验证程序,可以以以下形式使用: http:// symfony。 com / doc / current / reference / constraints / Email.html
我的问题是:如何在controlelr中使用此验证器来验证电子邮件地址?
这可以通过为用户使用PHP preg_match来实现,但是我的问题是,是否有可能使用已经内置于电子邮件验证程序中的Symfony。 p>
谢谢。
通过使用validateValue 方法的 Validator 服务
使用Symfony\Component\Validator\ \约束\电子邮件作为EmailConstraint;
// ...
公共功能customAction()
{
$ email =‘value_to_validate’;
// ...
$ emailConstraint = new EmailConstraint();
$ emailConstraint-> message =您的自定义错误消息;
$ errors = $ this-> get(’validator')-> validateValue(
$ email,
$ emailConstraint
);
//如果您的电子邮件地址有效,$ errors为空
//如果您的电子邮件地址无效,则包含验证错误消息
// ...
}
// ...
There is an email validator in symfony that can be used in a form: http://symfony.com/doc/current/reference/constraints/Email.html
My question is: How can I use this validator in my controlelr in order to validate an email address?
This is possible by using the PHP preg_match for usere, but my question is if there is a possibility to use the Symfony already built in email validator.
Thank you in advance.
By using validateValue method of the Validator service
use Symfony\Component\Validator\Constraints\Email as EmailConstraint;
// ...
public function customAction()
{
$email = 'value_to_validate';
// ...
$emailConstraint = new EmailConstraint();
$emailConstraint->message = 'Your customized error message';
$errors = $this->get('validator')->validateValue(
$email,
$emailConstraint
);
// $errors is then empty if your email address is valid
// it contains validation error message in case your email address is not valid
// ...
}
// ...
这篇关于Symfony2-如何在控制器中验证电子邮件地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!