【问题标题】:Symfony validation between 2 fields2 个字段之间的 Symfony 验证
【发布时间】:2020-10-24 19:21:33
【问题描述】:

我有一个包含 3 个字段的更改密码表单:

  1. currentPasword
  2. newPassword
  3. confirmNewPassword

我想验证newPassword 不等于当前的。

我可以验证它在表单使用的ChangePassword 实体中是否为空,例如,使用:

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
    $metadata->addPropertyConstraint('newPassword', new NotBlank());
}

但是我如何验证一个字段与另一个字段呢?我是否只需要对其进行硬编码,如果需要,该代码最好放在哪里?

【问题讨论】:

    标签: symfony symfony-forms symfony-validator


    【解决方案1】:

    我会为您的用户实体添加一个验证器约束。这样您就可以将 currentPassword 与 newPassword 进行比较。当然还有 newPassword 与 confirmNewPassword。

    例子:

    // src/Entity/Authentification/User.php
    namespace App\Entity\Authentification;
    
    use Symfony\Component\Validator\Constraints as Assert;
    use Symfony\Component\Validator\Context\ExecutionContextInterface;
    
    class User
    {
        // here you can add assert annotations (alternatively to your loadValidatorMetaData) 
        /**
         * @Assert\NotBlank(„Please enter current password“)
         */
        private currentPassword;
    
        private newPassword;
    
        private confirmNewPassword;
    
        //getter & setter go here
         
        /**
         * @Assert\Callback
         */
        public function validate(ExecutionContextInterface $context, $payload)
        {
             if ($this->getNewPasswort() === $this->getCurrentPassword()) {
                $context->buildViolation('Your new password must be different      from the current Password!')
                    ->atPath('newPassword')
                    ->addViolation();
            }
            if ($this->getNewPasswort() ==! $this->getConfirmNewPassword()) {
                $context->buildViolation('Your confirmed password is not equal to the new password!')
                    ->atPath('confirmNewPassword')
                    ->addViolation();
            } 
        }
    }
    
    

    使用此自定义验证,您可以在多个字段之间进行验证。但请记住,在您提交表单后会触发此验证。 AssertCallback 是通过在控制器中使用 $form->isValid() 触发的:

        if($form->isSubmitted() && $form->isValid()). 
    
    

    由于违规,您可以通过以下方式捕获失败的验证:

    
        if($form->isSubmitted() && !$form->isValid())
    
    

    您可以在 formType 和 html 输出中处理用户对违规的反馈。 (所以看看Symfony2 : How to get form validation errors after binding the request to the form

    参考资料:

    https://symfony.com/doc/current/validation/custom_constraint.html https://symfony.com/doc/current/reference/constraints/Callback.html

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 2014-10-07
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多