1

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

  1. currentPasword
  2. newPassword
  3. confirmNewPassword

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

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

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

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

4

1 回答 1

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

希望能帮助到你 :)

于 2020-07-04T09:56:18.323 回答