简体   繁体   中英

Symfony 2 Email Validator Null Value

I have implemented a forgotten password form and validate the provided email using Symfonys email constraint however it appears that it fails to recognise an empty or null value as an invalid email address even if I set the host and MX records check to true. To me that makes no sense. Am I missing something here or is that expected behaviour??

$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
    );

Look at the source of the validator: if an empty string or null is passed, it does nothing. In other words, empty values will always succeed.

So yep, it's expected behavior though there's a ticket about changing it.

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

    // ...
}

You'll need to use a combination of NotBlank and Email

<?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,
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM