亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Symfony 5 約束驗證:自定義錯誤消息

Symfony 5 約束驗證:自定義錯誤消息

PHP
人到中年有點甜 2022-09-17 21:01:26
我想使用SF 4.3上發布的新不承諾密碼:https://symfony.com/blog/new-in-symfony-4-3-compromised-password-validator我已經在我的驗證.yaml上設置了它,如下所示:App\Entity\User:    constraints:        - App\Validator\Constraints\ConstraintPassword: ~    properties:        plainPassword:            - Symfony\Component\Validator\Constraints\NotCompromisedPassword: ~它可以工作,但我想自定義錯誤消息,例如,直接在我的約束密碼驗證器上使用它.php:<?phpnamespace 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    }}也許它需要在我的約束密碼中實例化和自定義.php?但我不知道如何<?phpnamespace 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 回答

?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

您可以在驗證上傳遞該選項。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;

        }

    }

}


查看完整回答
反對 回復 2022-09-17
  • 1 回答
  • 0 關注
  • 121 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號