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

2022-08-30 17:57:29

symfony中有一个电子邮件验证器,可以以下形式使用:http://symfony.com/doc/current/reference/constraints/Email.html

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

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

提前感谢您。


答案 1

通过使用验证程序服务的验证值方法

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

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

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;
}

我希望这有帮助


推荐