当Type约束返回违规时如何退出复合字段验证?

时间:2017-02-02 08:14:57

标签: php symfony symfony-forms

假设我要验证电子邮件变量,该变量已提交给控制器操作:

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,我必须手动处理它,返回翻译的消息,注入翻译等等。

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

1 个答案:

答案 0 :(得分:1)

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

How to Sequentially Apply Validation Groups

希望这个帮助