Symfony2 - 如何验证控制器中的电子邮件地址

时间:2022-10-16 14:58:22

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?

我的问题是:我如何在我的控件中使用此验证器来验证电子邮件地址?

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.

先谢谢你。

5 个解决方案

#1


45  

By using validateValue method of the Validator service

通过使用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
    // ...
}
// ...

#2


14  

I wrote a post about validating email address(es) (one or many) outside of forms

我写了一篇关于验证表单之外的电子邮件地址(一个或多个)的帖子

http://konradpodgorski.com/blog/2013/10/29/how-to-validate-emails-outside-of-form-with-symfony-validator-component/

http://konradpodgorski.com/blog/2013/10/29/how-to-validate-emails-outside-of-form-with-symfony-validator-component/

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

我希望这有帮助

#3


10  

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...

我也是新人并且学习它,任何建议都将受到赞赏......

#4


6  

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

为什么没有人提到你可以使用'constraints'键在FormBuilder实例中验证它?首先,阅读文档使用没有类的表单

'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()
        ]);
    }

}

Result: Symfony2  - 如何验证控制器中的电子邮件地址

结果:

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:

如果要检查除消息之外的可用密钥,请转至以下文档:

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 \供应商\ symfony的\ symfony中的\ src \的Symfony \分量\验证\ \约束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; "

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

#5


0  

My solution for symfony 3 was the following:

我对symfony 3的解决方案如下:

use Symfony\Component\Validator\Constraints\Email as EmailConstraint;

$email = 'someinvalidmail@invalid.asdf';
// ... in the action then call
$emailConstraint = new EmailConstraint();

$errors = $this->get('validator')->validate(
    $email,
    $emailConstraint
);

$mailInvalid = count($errors) > 0;

#1


45  

By using validateValue method of the Validator service

通过使用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
    // ...
}
// ...

#2


14  

I wrote a post about validating email address(es) (one or many) outside of forms

我写了一篇关于验证表单之外的电子邮件地址(一个或多个)的帖子

http://konradpodgorski.com/blog/2013/10/29/how-to-validate-emails-outside-of-form-with-symfony-validator-component/

http://konradpodgorski.com/blog/2013/10/29/how-to-validate-emails-outside-of-form-with-symfony-validator-component/

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

我希望这有帮助

#3


10  

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...

我也是新人并且学习它,任何建议都将受到赞赏......

#4


6  

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

为什么没有人提到你可以使用'constraints'键在FormBuilder实例中验证它?首先,阅读文档使用没有类的表单

'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()
        ]);
    }

}

Result: Symfony2  - 如何验证控制器中的电子邮件地址

结果:

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:

如果要检查除消息之外的可用密钥,请转至以下文档:

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 \供应商\ symfony的\ symfony中的\ src \的Symfony \分量\验证\ \约束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; "

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

#5


0  

My solution for symfony 3 was the following:

我对symfony 3的解决方案如下:

use Symfony\Component\Validator\Constraints\Email as EmailConstraint;

$email = 'someinvalidmail@invalid.asdf';
// ... in the action then call
$emailConstraint = new EmailConstraint();

$errors = $this->get('validator')->validate(
    $email,
    $emailConstraint
);

$mailInvalid = count($errors) > 0;