【发布时间】:2020-03-25 09:55:41
【问题描述】:
我了解如何在表单类型等中应用约束。
但在实施密码重置的情况下,我需要检查电子邮件是否存在,如果不存在则错误。
如何在 Symfony 4+ 中实现这一目标?
这似乎没有解决我的问题:
【问题讨论】:
-
显示控制器代码可能会有所帮助。我不太明白这个问题。
标签: symfony validation symfony4
我了解如何在表单类型等中应用约束。
但在实施密码重置的情况下,我需要检查电子邮件是否存在,如果不存在则错误。
如何在 Symfony 4+ 中实现这一目标?
这似乎没有解决我的问题:
【问题讨论】:
标签: symfony validation symfony4
您可以为表单输入字段指定自定义约束。 见:https://symfony.com/doc/current/validation/custom_constraint.html
对于自定义约束,您需要像这样指定约束和验证器类:
/**
* @Annotation
*/
class NonExistingEmail extends Constraint
{
public $message = 'Email does not exist';
}
class NonExistingEmailValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof NonExistingEmail) {
throw new UnexpectedTypeException($constraint, NonExistingEmail::class);
}
// custom constraints should ignore null and empty values to allow
// other constraints (NotBlank, NotNull, etc.) take care of that
if (null === $value || '' === $value) {
return;
}
$user = $this->userRepository->findOneBy(["email" => $value])
if (!$user) {
$this->context->buildViolation($constraint->message)
->addViolation();
}
}
}
【讨论】: