我会为您的用户实体添加一个验证器约束。这样您就可以将 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
希望能帮助到你 :)