我了解在表单类型等中如何应用约束。
但是在实施密码重设的情况下,我需要检查是否存在电子邮件,如果不存在,则要检查错误。
如何在Symfony 4+中实现这一目标?
这似乎无法解决我的问题:
密码重置表单可以是有效的,但具有有效的电子邮件地址,但数据库中不存在。
有效性规则是您要验证的表单/实体的固有属性,通常不应要求访问您的数据存储。
如果要重置用户密码,则适当的处理方法是:
您可以为表单输入字段指定自定义约束。参见: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();
}
}
}