按顺序
此约束允许您应用一组规则,这些规则应逐步验证,允许在首次出现违规时中断验证。
作为 Sequentially
无法解决的情况的替代方案,您可以考虑使用 GroupSequence,它可以提供更多控制。
适用于 | 属性或方法 |
类 | 按顺序 |
验证器 | SequentiallyValidator |
基本用法
假设您有一个 Place
对象,其 $address
属性必须符合以下要求
- 它是一个非空白字符串
- 至少 10 个字符长
- 具有特定格式
- 并且可以使用外部服务进行地理定位
在这些情况下,您可能会遇到三个问题
- 如果实际值不是字符串(由
Type
强制执行),Length
或Regex
约束可能会因 UnexpectedValueException 异常而严重失败。 - 您可能会为同一属性收到多条错误消息。
- 您可能会执行无用且繁重的外部调用来对地址进行地理定位,而格式无效。
您可以按顺序验证每个约束来解决这些问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// src/Localization/Place.php
namespace App\Localization;
use App\Validator\Constraints as AcmeAssert;
use Symfony\Component\Validator\Constraints as Assert;
class Place
{
#[Assert\Sequentially([
new Assert\NotNull,
new Assert\Type('string'),
new Assert\Length(min: 10),
new Assert\Regex(Place::ADDRESS_REGEX),
new AcmeAssert\Geolocalizable,
])]
public string $address;
}
这项工作,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。