atk4 / validate
敏捷数据 - 验证器插件
5.0.0
2024-04-08 10:33 UTC
Requires
- php: >=7.4 <8.4
- atk4/data: ~5.0.0
- vlucas/valitron: ^1.4
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-08 10:55:52 UTC
README
这是敏捷数据(https://github.com/atk4/data)的验证器插件。
它底层使用 https://github.com/vlucas/valitron。
使用方法
// add model fields $model->addField('name'); $model->addField('age', ['type' => 'number']); $model->addField('type', ['required' => true, 'enum' => ['dog', 'ball']]); $model->addField('tail_length', ['type' => 'number']); // add validator to your model // also will register itself as $model->validator property $v = new \Atk4\Validate\Validator($model); // set simple validation rule for one field // ->rule($field, $rules) $v->rule('name', [ 'required', ['lengthMin', 3] ]); // set multiple validation rules in one shot // ->rules($array_of_rules) // [field=>rules] $v->rules([ 'name' => ['required', ['lengthMin',3]], 'age' => ['integer', ['min',0], ['max',99]], 'tail_length' => ['integer', ['min',0]], ]); // set validation rules based on value of another field // if type=dog, then sets fields age and tail_length as required // ->if($condition, $then_array_of_rules, $else_array_of_rules) $v->if(['type'=>'dog'], [ 'age' => ['required'], 'tail_length' => ['required'], ], [ 'tail_length' => [ ['equals',''] ], // balls don't have tail ]); // you can also pass multiple conditions which will be treated as AND conditions $v->if(['type'=>'dog', 'age'=>50], $rules_if_true, $rules_if_false); // you can also set custom error message like this: $v->rule('age', [ ['min', 3, 'message'=>'Common! {field} to small'] ]); // and you will get this "Common! Age to small"
您也可以传递回调而不是规则数组。回调函数接收这些参数 $field, $value, $args, $data 并应返回 true/false。
更多示例请查看 /tests
目录。