Stop validation on first error flag in Symfony2?

2019-05-03 07:39发布

I'm searching for informations if there is some kind of flag/option that force symfony2 validation stop on first error in validation chain. For example I have three validators on my email field:

email:
    - NotBlank: { groups: [ send_activation_email ] }
    - Length: { min: 6, max: 80, charset: UTF-8, groups: [ send_activation_email ] }
    - Email: { groups: [ send_activation_email ] }

I want to stop validation after first error. How can I achieve that? I read similar questions:

Symfony2 : Validation Halt on First Error

How to stop validation on constraint failure in Symfony2

Symfony-2 gives more than one validation error message

Last one is quite good but is there any way to do this without using validation groups every time, when there are more than one validator? I read somewhere that in Symfony 2.2 there will be a flag or option for this, but I have 2.2.1 version and can't find such option.

2条回答
Melony?
2楼-- · 2019-05-03 08:20

You can use the Chain validator for that purpose: https://gist.github.com/rybakit/4705749

Here's an example in plain PHP:

<?php

use Symfony\Component\Validator\Constraints\Date;
use Symfony\Component\Validator\Constraints\Type;
use Acme\Validator\Constraints\Chain;

$constraint = new Chain([new Type('string'), new Date()]);

In XML:

<!-- src/Acme/DemoBundle/Resources/config/validation.xml -->

<class name="Acme\DemoBundle\Entity\AcmeEntity">
    <property name="date">
        <constraint name="Acme\Validator\Constraints\Chain">
            <option name="constraints">
                <constraint name="Type">
                    <option name="type">string</option>
                </constraint>
                <constraint name="Date" />
            </option>
        </constraint>
    </property>
</class>

But be aware that if you want to have nested Chain constraints, like:

<?php

$constraint = new Chain([
    new Callback(...),
    new Chain([new Type('string'), new Date()]),
]);

you have to override the validator.validator_factory symfony service to fix the issue with handling nested constraints in the current implementation: https://github.com/symfony/Validator/blob/fc0650c1825c842f9dcc4819a2eaff9922a07e7c/ConstraintValidatorFactory.php#L48.

See the NoCacheConstraintValidatorFactory.php file from the gist to get an idea how it could be solved.

查看更多
你好瞎i
3楼-- · 2019-05-03 08:31

As of Symfony 2.3 you can do this using Group Sequences (though form support for group sequences might be spotty).

查看更多
登录 后发表回答