Symfony 2电子邮件验证器空值

时间:2013-10-19 13:11:36

标签: php validation email symfony

我已经实现了一个忘记的密码表单并使用Symfonys电子邮件约束验证提供的电子邮件,但是即使我将主机和MX记录设置为true,它似乎也无法将空值或空值识别为无效的电子邮件地址。对我来说毫无意义。我在这里遗漏了什么或是预期的行为吗?

$email = $request->request->get('email');

$emailValidator = new Email();
$emailValidator->message = 'Invalid email address';

// use the validator to validate the value
$errorList = $this->get('validator')->validateValue(
        $email,
        $emailValidator
    );

1 个答案:

答案 0 :(得分:5)

查看验证器的the source:如果传递空字符串或null,则不执行任何操作。换句话说,空值总是会成功。

所以,这是预期的行为,虽然有关于改变它的票。

<?php
/**
 * @author Bernhard Schussek <[...]>
 *
 * @api
 */
class EmailValidator extends ConstraintValidator
{
    /**
     * {@inheritDoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (null === $value || '' === $value) {
            return;
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string) $value;
        $valid = filter_var($value, FILTER_VALIDATE_EMAIL);

        if ($valid) {
            $host = substr($value, strpos($value, '@') + 1);

            // Check for host DNS resource records
            if ($valid && $constraint->checkMX) {
                $valid = $this->checkMX($host);
            } elseif ($valid && $constraint->checkHost) {
                $valid = $this->checkHost($host);
            }
        }

        if (!$valid) {
            $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
        }
    }

    // ...
}

您需要使用NotBlankEmail

的组合
<?php
use Symfony\Component\Validator\Constraints as Assert;

$emailValidator = new Assert\Email();
$emailValidator->message = 'Invalid email address';

$validator->validateValue($the_email, array(
    new Assert\NotBlank(),
    $emailValidator,
));