mezuno / php-validator
PHP 数据验证器
Requires
- php: ^8.1
- adbario/php-dot-notation: ^3.3
README
RulesValidator 文档
目录
规则
截至当前(2023年8月28日),以下规则可用于验证
和派生规则
规则方法
required() 和 nullable()
每条规则至少有两个方法:required() 和 nullable()
required() 负责字段的必填性
nullable() 负责字段的必填性和是否可以为 null
注意
默认字段不是必填的
$rules = [ 'some_field' => IntRules::make()->required(), 'another_field' => IntRules::make()->nullable(), ];
警告
required() 和 nullable() 是互斥的规则
这意味着不能同时指定两者,否则将应用最后的规则
min() 和 max()
所有类型为 NumericRules 的规则都有 min() 和 max() 方法
这些方法分别接受字段的最小值和最大值作为参数
示例
$rules = [ 'some_integer_field' => IntRules::make()->min(1)->max(3), ];
同样,StringRules 也有相同的方法,但含义不同。对于 NumericRules,min() 和 max() 表示具体的值,而对于字符串,min() 和 max() 表示对字符串长度的限制。
示例
$rules = [ 'password' => StringRules::make()->min(8)->max(32), ];
items()
ArrayRules 包含一个 items() 方法,接受用于验证字段数组或子数组字段的规则
ArrayRules 的 items() 方法有两个参数:第一个参数是用于验证数组字段规则的数组,第二个参数是标志 $nested,它指示是否存在嵌套
示例:具有一个必填字段的数组
$rules = [ 'some_array_field' => ArrayRules::make()->items([ 'some_array_item' => StringRules::make()->required(), ]), ];
有效
{ "some_array_field": { "some_nested_array_item": 2 } }
无效
{ "some_another_array_field": [ { "some_nested_array_item": 2 } ] }
示例:验证嵌套数组的数组
注意 验证嵌套数组时,第二个参数为 true
$rules = [ 'some_array_field' => ArrayRules::make()->items([ 'some_nested_array_item' => IntRules::make()->required(), ], true), ];
有效
{ "some_another_array_field": [ { "some_nested_array_item": 2 } ] }
无效
{ "some_array_field": { "some_nested_array_item": 2 } }
exists()
接受存储库的第一个参数,以及该存储库的第二个参数的方法。
示例
$rules = [ 'card_barcode' => StringRules::make()->exists(CardRepository::class, 'findByBarcode'), ];
validationExceptions() 方法
validationExceptions() 方法用于设置验证错误的自定义消息
为了为某个规则设置自定义 Exception,只需在返回的数组中指定字段的键、规则的键和 Exception 即可
示例
$messages = [ 'field.required' => 'Some custom message for required', 'field.type' => 'Some custom message for type' 'field.min' => 'Some custom message for min' 'field.max' => 'Some custom message for max' 'field.exists' => 'Some custom message for exists' 'phone_field.phone' => 'Some custom message for phone'; 'email_field.email' => 'Some custom message for email'; ];
在此示例中,如果请求中未传递字段 field,则将抛出指定的 Exception。
还可以按照以下方式为数组元素指定自定义 Exception
$rules = [ 'product.items.price' => 'Item product[price] required.'; ];
如果需要为嵌套数组元素添加自定义消息,请使用 nested_items 键
$rules = [ 'products.nested_items.price' => 'Item products[][price] required.'; ];