Symfony Validator Extras,用于更简单地处理复杂情况
v0.1.0
2016-10-18 08:41 UTC
Requires
- symfony/validator: ^3.1
Requires (Dev)
- phpspec/phpspec: ^3.1
- phpunit/phpunit: ^5.6
This package is not auto-updated.
Last update: 2024-09-14 20:40:46 UTC
README
为了简化请求验证并减少样板代码,此包提供了一组额外的约束。
Json 和 FixedJson 约束
如果您正在处理 Json 请求,您可能不喜欢 Collection
验证器。作为替代,这个库为您提供了两个额外的约束:JsonValidator
和 FixedJsonValidator
。
JsonValidator
和 FixedJsonValidator
之间的区别在于它们使用不同的 allowExtraFields
选项值。 FixedJson
不允许额外字段,而 Json
则忽略它。
快捷方式
此验证器为常见验证器提供了一些快捷方式
$rules = new FixedJson([ 'foo' => 'string', 'bar' => 'email', 'buz' => 'datetime', ]);
这等同于
$rules = new Collection([ 'foo' => [new NotNull(), new Type('string')], 'bar' => [new NotNull(), new Email()], 'buz' => [new NotNull(), new DateTime()] ]);
可用快捷方式的列表
空安全
默认情况下,所有约束(除了 null
)快捷方式都扩展为 NotNull
约束。如果 null
是您可接受的有效值,您只需在快捷方式的开始处添加问号。因此,这些规则将是等效的
$rules = new Json([
'foo' => '?string',
'bar' => 'string'
]);
$equivalent = new Collection([
'allowExtraFields' => true,
'fields' => [
'foo' => [new Type('string')],
'bar' => [new NotNull(), new Type('string')]
]
]);
语法取自 PHP 7.1
可选字段
如果您的 Json 请求具有可选键,那么您可能需要编写如下内容
$rules = new Collection([ 'foo' => new Optional([new NotNull(), new Type('string')]) ]);
使用 JsonValidator
,相同的规则可以写成
$rules = new Json([ 'foo?' => 'string' ]);
请注意,如果您手动提供有关字段是否为必需的信息,则问号(?
)将被忽略。因此,使用此规则
$fules = new Json([ 'foo?' = new Required([new NotNull()]), 'bar??' => 'string', ])
验证器将期望 foo?
包含非空值。属性 bar?
被视为可选,因为它在其末尾有问号(?
)。