gpt4 book ai didi

validation - 停止验证 Symfony2 中的第一个错误标志?

转载 作者:行者123 更新时间:2023-12-04 19:09:40 24 4
gpt4 key购买 nike

如果有某种标志/选项强制 symfony2 验证在验证链中的第一个错误时停止,我正在搜索信息。例如,我的 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 ] }

我想在第一个错误后停止验证。我怎样才能做到这一点?我读过类似的问题:

Symfony2 : Validation Halt on First Error

How to stop validation on constraint failure in Symfony2

Symfony-2 gives more than one validation error message

最后一个非常好,但是当有多个验证器时,有没有什么方法可以不用每次都使用验证组?我在某处读到在 Symfony 2.2 中会有一个标志或选项,但我有 2.2.1 版本并且找不到这样的选项。

最佳答案

您可以使用 Chain为此目的的验证器: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约束,例如:

<?php

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

你必须覆盖 validator.validator_factory symfony 服务来解决当前实现中处理嵌套约束的问题: https://github.com/symfony/Validator/blob/fc0650c1825c842f9dcc4819a2eaff9922a07e7c/ConstraintValidatorFactory.php#L48 .

NoCacheConstraintValidatorFactory.php文件中的要点,以了解如何解决它。

关于validation - 停止验证 Symfony2 中的第一个错误标志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16359928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com