Stop validation on first error flag in Symfony2?

寵の児 提交于 2019-12-07 05:35:46

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/16359928/stop-validation-on-first-error-flag-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!