php Symfony2 - 如何在控制器中验证电子邮件地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18316166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Symfony2 - How to validate an email address in a controller
提问by Milo?
There is an email validator in symfony that can be used in a form: http://symfony.com/doc/current/reference/constraints/Email.html
symfony 中有一个电子邮件验证器,可以以一种形式使用: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?
我的问题是:如何在我的 controlelr 中使用此验证器来验证电子邮件地址?
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.
这可以通过使用 PHP preg_match 来实现,但我的问题是是否有可能使用已经内置在电子邮件验证器中的 Symfony。
Thank you in advance.
先感谢您。
回答by Ahmed Siouani
By using validateValuemethod of the Validatorservice
通过使用Validator服务的validateValue方法
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
// ...
}
// ...
回答by Konrad Podgórski
I wrote a post about validating email address(es) (one or many) outside of forms
我写了一篇关于验证表单之外的电子邮件地址(一个或多个)的帖子
It also covers a common bug where you validate against Email Constraint and forget about NotBlank
它还涵盖了一个常见的错误,您可以根据电子邮件约束进行验证而忘记 NotBlank
/**
* Validates a single email address (or an array of email addresses)
*
* @param array|string $emails
*
* @return array
*/
public function validateEmails($emails){
$errors = array();
$emails = is_array($emails) ? $emails : array($emails);
$validator = $this->container->get('validator');
$constraints = array(
new \Symfony\Component\Validator\Constraints\Email(),
new \Symfony\Component\Validator\Constraints\NotBlank()
);
foreach ($emails as $email) {
$error = $validator->validateValue($email, $constraints);
if (count($error) > 0) {
$errors[] = $error;
}
}
return $errors;
}
I hope this helps
我希望这有帮助
回答by Amit Malakar
If you're creating the form in the controller itself and want to validate email in the action, then the code will look like this.
如果您在控制器本身中创建表单并希望在操作中验证电子邮件,那么代码将如下所示。
// add this above your class
use Symfony\Component\Validator\Constraints\Email;
public function saveAction(Request $request)
{
$form = $this->createFormBuilder()
->add('email', 'email')
->add('siteUrl', 'url')
->getForm();
if ('POST' == $request->getMethod()) {
$form->bindRequest($request);
// the data is an *array* containing email and siteUrl
$data = $form->getData();
// do something with the data
$email = $data['email'];
$emailConstraint = new Email();
$emailConstraint->message = 'Invalid email address';
$errorList = $this->get('validator')->validateValue($email, $emailConstraint);
if (count($errorList) == 0) {
$data = array('success' => true);
} else {
$data = array('success' => false, 'error' => $errorList[0]->getMessage());
}
}
return $this->render('AcmeDemoBundle:Default:update.html.twig', array(
'form' => $form->createView()
));
}
I'm also new and learning it, any suggestions will be appreciated...
我也是新手,正在学习它,任何建议将不胜感激...
回答by DevWL
Why does no one mention that you can validate it with in FormBuilder instance using 'constraints' key ??? First of all, read documentation Using a Form without a Class
为什么没有人提到您可以使用“约束”键在 FormBuilder 实例中验证它???首先,阅读文档Using a Form without a Class
'constraints' =>[
new Assert\Email([
'message'=>'This is not the corect email format'
]),
new Assert\NotBlank([
'message' => 'This field can not be blank'
])
],
Works fine with symfony 3.1
适用于 symfony 3.1
Example:
例子:
namespace SomeBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type;
use Symfony\Component\Validator\Constraints as Assert;
class DefaultController extends Controller
{
/**
* @Route("kontakt", name="_kontakt")
*/
public function userKontaktAction(Request $request) // access for all
{
$default = array('message' => 'Default input value');
$form = $this->createFormBuilder($default)
->add('name', Type\TextType::class,[
'label' => 'Nazwa firmy',
])
->add('email', Type\EmailType::class,[
'label' => 'Email',
'constraints' =>[
new Assert\Email([
'message'=>'This is not the corect email format'
]),
new Assert\NotBlank([
'message' => 'This field can not be blank'
])
],
])
->add('phone', Type\TextType::class,[
'label' => 'Telefon',
])
->add('message', Type\TextareaType::class,[
'label' => 'Wiadomo??',
'attr' => [
'placeholder' => 'Napisz do nas ... '
],
])
->add('send', Type\SubmitType::class,[
'label' => 'Wy?lij',
])
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// data is an array with "name", "email", and "message" keys
$data = $form->getData();
// send email
// redirect to prevent resubmision
var_dump($data);
}
return $this->render('SomeBundle:Default:userKontakt.html.twig', [
'form' => $form->createView()
]);
}
}
See the documentaion about available validation types. http://api.symfony.com/3.1/Symfony/Component/Validator/Constraints.html
请参阅有关可用验证类型的文档。 http://api.symfony.com/3.1/Symfony/Component/Validator/Constraints.html
If you want to check what are the available keys other than message, go to documentation at:
如果要检查除 message 之外的可用密钥是什么,请转到以下位置的文档:
http://symfony.com/doc/current/reference/constraints/Email.html
http://symfony.com/doc/current/reference/constraints/Email.html
or navigate to:
或导航到:
YourProject\vendor\symfony\symfony\src\Symfony\Component\Validator\Constraints\Email.php
YourProject\vendor\symfony\symfony\src\Symfony\Component\Validator\Constraints\Email.php
from there, you will be able to see what else is available.
从那里,您将能够看到还有什么可用的。
public $message = 'This value is not a valid email address.'; public $checkMX = false; public $checkHost = false; public $strict; "
public $message = 'This value is not a valid email address.'; public $checkMX = false; public $checkHost = false; public $strict; "
Also note that I created and validated form inside the controller which is not a best practice and should only be used for forms, which you will never reuse anywhere else in your application.
另请注意,我在控制器内创建并验证了表单,这不是最佳实践,仅应用于表单,您永远不会在应用程序的其他任何地方重用表单。
Best practice is to create forms in a separated directory under YourBundle/Form. Move all the code to your new ContactType.php class. (don't forget to import FormBuilder class there as it will not extend your controller and will not have access to this class through '$this')
最佳做法是在 YourBundle/Form 下的单独目录中创建表单。将所有代码移至新的 ContactType.php 类。(不要忘记在那里导入 FormBuilder 类,因为它不会扩展您的控制器并且无法通过“$this”访问此类)
[inside ContactType class:]
[内部 ContactType 类:]
namespace AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type;
use Symfony\Component\Validator\Constraints as Assert;
[inside your controller:]
[在您的控制器内:]
use YourBundle/Form/ContactType;
// use ...
//...
$presetData = []; //... preset form data here if you want to
$this->createForm('AdminBundle\Form\FormContactType', $presetData) // instead of 'createFormBuilder'
->getForm();
// render view and pass it to twig templet...
// or send the email/save data to database and redirect the form
回答by totas
My solution for symfony 3 was the following:
我对 symfony 3 的解决方案如下:
use Symfony\Component\Validator\Constraints\Email as EmailConstraint;
$email = '[email protected]';
// ... in the action then call
$emailConstraint = new EmailConstraint();
$errors = $this->get('validator')->validate(
$email,
$emailConstraint
);
$mailInvalid = count($errors) > 0;