【问题标题】:Symfony 4+ form validation done in a controller action?Symfony 4+ 表单验证在控制器操作中完成?
【发布时间】:2020-03-25 09:55:41
【问题描述】:

我了解如何在表单类型等中应用约束。

但在实施密码重置的情况下,我需要检查电子邮件是否存在,如果不存在则错误。

如何在 Symfony 4+ 中实现这一目标?

这似乎没有解决我的问题:

https://symfony.com/doc/current/validation/raw_values.html

【问题讨论】:

  • 显示控制器代码可能会有所帮助。我不太明白这个问题。

标签: symfony validation symfony4


【解决方案1】:

您可以为表单输入字段指定自定义约束。 见: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();
        }
    }
}

【讨论】:

  • 我不知道为什么有人对你的答案投了反对票,也没有解释为什么......我对你的答案投了赞成票,但我还没有尝试过,所以我无法确认它是否解决了我的问题问题。我希望这周的某个时候,如果它有效,我会接受你的回答。谢谢你的时间:)
猜你喜欢
  • 1970-01-01
  • 2019-01-12
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多