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

时间:2020-02-12 11:07:25

标签: php symfony validation

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

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

App\Entity\User:
    constraints:
        - App\Validator\Constraints\ConstraintPassword: ~
    properties:
        plainPassword:
            - Symfony\Component\Validator\Constraints\NotCompromisedPassword: ~

它可以工作,但是我想自定义错误消息,例如,直接在我的ConstraintPasswordValidator.php上使用它:

<?php

namespace App\Validator\Constraints;

use App\Entity\User;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\NotCompromisedPassword;
use Symfony\Component\Validator\ConstraintValidator;

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
    }
}

也许需要在我的ConstraintPassword.php中实例化和自定义它?但是我不知道怎么办

<?php

namespace App\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

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;
    }
}

1 个答案:

答案 0 :(得分:1)

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

App\Entity\User:
    properties:
        plainPassword:
            - Symfony\Component\Validator\Constraints\NotCompromisedPassword:
                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;
        }
    }
}