Symfony 5 约束验证:自定义错误消息



我想使用SF 4.3上发布的新NotCompromisedPassword: https://symfony.com/blog/new-in-symfony-4-3-compromised-password-validator

我已经在我的validation.yaml上设置了它,如下所示:

AppEntityUser:
constraints:
- AppValidatorConstraintsConstraintPassword: ~
properties:
plainPassword:
- SymfonyComponentValidatorConstraintsNotCompromisedPassword: ~

它可以工作,但我想自定义错误消息,例如,直接在我的约束密码验证器上使用它.php :

<?php
namespace AppValidatorConstraints;
use AppEntityUser;
use SymfonyComponentValidatorConstraint;
use SymfonyComponentValidatorConstraintsNotCompromisedPassword;
use SymfonyComponentValidatorConstraintValidator;
class ConstraintPasswordValidator extends ConstraintValidator
{
/**
* @param User $user
* @param Constraint $constraint
*/
public function validate($user, Constraint $constraint)
{
if (strlen($user->getPlainPassword()) < 8 || strlen($user->getPlainPassword() < 35)) {
$this->context->buildViolation($constraint->lengthError)
->addViolation();
}
// Doing something like that
$notCompromised = new NotCompromisedPassword();
$notCompromised->message = "My custom error message";
//Then, build the violation if password leaked
}
}

也许它需要在我的约束密码中实例化和自定义.php?但我不知道怎么做

<?php
namespace AppValidatorConstraints;
use SymfonyComponentValidatorConstraint;
class ConstraintPassword extends Constraint
{
public $lengthError = 'Erreur : La longueur du mot de passe doit être comprise entre 8 et 35 caractères';
public function validatedBy()
{
return get_class($this).'Validator';
}
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}

您可以在 validation.yaml 上传递message选项

AppEntityUser:
properties:
plainPassword:
- SymfonyComponentValidatorConstraintsNotCompromisedPassword:
message: "You error message"

但是,如果要将约束验证到验证器中,则可以使用:

class MyValidator extends ConstraintValidator
{
public function validate($value, Constraint $chain)
{
// Previous check...
$groups = $this->context->getGroup();
$violations = $this->context->getViolations();
$current = $violations->count();
// Execute the new constraint
$this->context->getValidator()
->inContext($this->context)
->validate($value, new MyOtherConstraint(), $groups);
// Check if the constraint has failed
if ($violations->count() !== $current) {
return;
}
}
}

最新更新