danielz / shape-validator-php
简单的(数组)形状验证器。
v1.0.0
2022-01-28 12:20 UTC
Requires
- php: ^7.4|^8.0
Requires (Dev)
- pestphp/pest: ^1.21
README
为形状定义所有可能的字段并设置其规则。任何不在定义集中的字段都会触发错误。
用法
try { $shape = [ 'name' => 'required|string', 'phone' => 'required|numeric', 'notes' => 'string', 'data' => 'any', ]; $shape_validator = new ShapeValidator($shape); $shape_validator->validate([ 'name' => 'Hello, world!', // valid 'extra' => null, // this will trigger an error ]); } catch(ShapeException $exception) { // getValidationErrors() returns an array like ['field name' => 'error message'] log($exception->getValidationErrors()); }
可用规则
required
- 字段必须存在nullable
- 字段可以接受null值string
- 如果字段值已设置,它必须是一个有效的字符串numeric
- 如果字段值已设置,它必须具有有效的数值bool
/boolean
- 如果字段值已设置,它必须是一个有效的布尔值(验证使用类型比较===
)any
- 允许任何值