查看验证器的来源:如果传递的是空字符串或 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));
}
}
// ...
}
您需要使用NotBlank
和的组合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,
));