停止对Symfony2中的第一个错误标志进行验证? [英] Stop validation on first error flag in Symfony2?

查看:77
本文介绍了停止对Symfony2中的第一个错误标志进行验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有某种标志/选项会强制symfony2验证在验证链中的第一个错误时停止,我正在搜索信息.例如,我在email字段上有三个验证器:

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:在出现第一个错误时验证暂停

如何在Symfony2中停止对约束失败的验证

Symfony-2给出了多个验​​证错误消息

最后一个是相当不错的,但是当验证器不止一个时,是否有任何方法可以在不使用验证组的情况下每次执行此操作?我在Symfony 2.2的某个地方读到有一个标志或选项,但是我有2.2.1版本,找不到这样的选项.

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.

推荐答案

您可以为此目的使用Chain验证器: https://gist.github.com/rybakit/4705749

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

这是纯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()]);

在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>

但是请注意,如果您想嵌套Chain约束,例如:

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()]),
]);

您必须重写validator.validator_factory symfony服务以解决当前实现中嵌套嵌套约束的问题:

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.

请参阅要点中的NoCacheConstraintValidatorFactory.php文件,以了解如何解决该问题.

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

这篇关于停止对Symfony2中的第一个错误标志进行验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆