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

Mil*_*loš 22 php validation email-validation symfony

symfony中有一个可以在表单中使用的电子邮件验证器:http://symfony.com/doc/current/reference/constraints/Email.html

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

这可以通过使用PHP preg_match来实现,但我的问题是是否有可能使用已经内置在电子邮件验证器中的Symfony.

先感谢您.

Ahm*_*ani 52

通过使用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
    // ...
}
// ...
Run Code Online (Sandbox Code Playgroud)

  • 请注意,自Symfony 2.5起,不推荐使用validateValue,而应使用validate. (15认同)
  • 自版本2.5起不再使用Validator服务,将在3.0中删除.应该使用Validator\RecursiveValidator (2认同)

Kon*_*ski 15

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

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

它还包含一个常见的错误,您可以在其中验证电子邮件约束并忘记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;
}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助


小智 10

如果您在控制器本身中创建表单并想要在操作中验证电子邮件,则代码将如下所示.

// 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()
   ));
}
Run Code Online (Sandbox Code Playgroud)

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


Dev*_*vWL 7

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

'constraints' =>[
    new Assert\Email([
        'message'=>'This is not the corect email format'
    ]),
    new Assert\NotBlank([
        'message' => 'This field can not be blank'
    ])
],
Run Code Online (Sandbox Code Playgroud)

适用于symfony 3.1

例:

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

}
Run Code Online (Sandbox Code Playgroud)

结果: 在此输入图像描述

请参阅有关可用验证类型的文档. http://api.symfony.com/3.1/Symfony/Component/Validator/Constraints.html

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

http://symfony.com/doc/current/reference/constraints/Email.html

或导航至:

YourProject \供应商\ symfony的\ symfony中的\ src \的Symfony \分量\验证\ \约束Email.php

从那里,你将能够看到还有什么可用.

public $message = 'This value is not a valid email address.';

public $checkMX = false;

public $checkHost = false;

public $strict; "
Run Code Online (Sandbox Code Playgroud)

另请注意,我在控制器中创建并验证了表单,这不是最佳实践,只应用于表单,您永远不会在应用程序的任何其他位置重复使用.

最佳做法是在YourBundle/Form下的单独目录中创建表单.将所有代码移动到新的ContactType.php类.(不要忘记在那里导入FormBuilder类,因为它不会扩展你的控制器,也无法通过'$ this'访问这个类)

[在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;
Run Code Online (Sandbox Code Playgroud)

[在你的控制器里面]

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
Run Code Online (Sandbox Code Playgroud)