Reputation: 2486
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
);
Upvotes: 1
Views: 1793
Reputation: 2359
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,
));
Upvotes: 5