如何在违反类型约束 returns 时退出复合字段验证?

How to exit composite field validation when Type constraint returns violation?

假设我想验证提交给控制器操作的电子邮件变量:

use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Type;

$constraints = new Collection([
    'fields' => [
        'email' =>  [
            new Type([
                 'type' => 'string',
                 'message' => static::ERROR_EMAIL_INVALID,
            ]),
            new NotBlank([
                'message' => static::ERROR_EMAIL_REQUIRED,
            ]),
            new Email([
                'message' => static::ERROR_EMAIL_INVALID,
            ]),
            new Length([
                'max'        => 128,
                'maxMessage' => static::ERROR_EMAIL_TOO_LONG,
            ]),
        ],
    ],
]);

如果用户提交email[]=1,那么UnexpectedTypeException将被抛出,我必须手动处理它,return翻译的消息,注入翻译等

有没有办法告诉 Symfony 验证器首先验证 Type 并在 Type 失败时忽略其他约束(仅 return Type 错误)?

为了避免出现多个错误消息,您可以使用此处所述的 GroupSequence 功能:

How to Sequentially Apply Validation Groups

希望对您有所帮助