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

时间:2013-08-19 14:20:09

标签: php validation symfony email-validation

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

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

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

提前谢谢。

6 个答案:

答案 0 :(得分:52)

使用validateValue服务的Validator方法

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

答案 1 :(得分: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;
}

我希望这会有所帮助

答案 2 :(得分: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()
   ));
}

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

答案 3 :(得分:7)

为什么没有人提到您可以使用'约束'在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'
    ])
],
  

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

}

结果: enter image description here

请参阅有关可用验证类型的文档。 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; "

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

最佳做法是在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;

[在您的控制器内部]:

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

答案 4 :(得分:1)

我对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;

答案 5 :(得分:0)

另一种方法-您可以使用egulias/EmailValidator bundle.

composer require egulias/email-validator

可以不带容器

使用
    use Egulias\EmailValidator\EmailValidator;
    use Egulias\EmailValidator\Validation\RFCValidation;
    
    $validator = new EmailValidator();
    $validator->isValid("example@example.com", new RFCValidation());

还捆绑包可以使用DNSCheckValidation验证DNS