验证场景

版本新增功能
5.0.4增加hasScene方法用于检查是否存在验证场景

可以在定义验证规则的时候定义场景,并且验证不同场景的数据,例如:

  1. $rule = [
  2. 'name' => 'require|max:25',
  3. 'age' => 'number|between:1,120',
  4. 'email' => 'email',
  5. ];
  6. $msg = [
  7. 'name.require' => '名称必须',
  8. 'name.max' => '名称最多不能超过25个字符',
  9. 'age.number' => '年龄必须是数字',
  10. 'age.between' => '年龄只能在1-120之间',
  11. 'email' => '邮箱格式错误',
  12. ];
  13. $data = [
  14. 'name' => 'thinkphp',
  15. 'age' => 10,
  16. 'email' => 'thinkphp@qq.com',
  17. ];
  18. $validate = new Validate($rule);
  19. $validate->scene('edit', ['name', 'age']);
  20. $result = $validate->scene('edit')->check($data);

表示验证edit场景(该场景定义只需要验证name和age字段)。

如果使用了验证器,可以直接在类里面定义场景,例如:

  1. namespace app\index\validate;
  2. use think\Validate;
  3. class User extends Validate
  4. {
  5. protected $rule = [
  6. 'name' => 'require|max:25',
  7. 'age' => 'number|between:1,120',
  8. 'email' => 'email',
  9. ];
  10. protected $message = [
  11. 'name.require' => '名称必须',
  12. 'name.max' => '名称最多不能超过25个字符',
  13. 'age.number' => '年龄必须是数字',
  14. 'age.between' => '年龄只能在1-120之间',
  15. 'email' => '邮箱格式错误',
  16. ];
  17. protected $scene = [
  18. 'edit' => ['name','age'],
  19. ];
  20. }

然后再需要验证的地方直接使用 scene 方法验证

  1. $data = [
  2. 'name' => 'thinkphp',
  3. 'age' => 10,
  4. 'email' => 'thinkphp@qq.com',
  5. ];
  6. $validate = new \app\index\validate\User($rule);
  7. $result = $validate->scene('edit')->check($data);

可以在定义场景的时候对某些字段的规则重新设置,例如:

  1. namespace app\index\validate;
  2. use think\Validate;
  3. class User extends Validate
  4. {
  5. protected $rule = [
  6. 'name' => 'require|max:25',
  7. 'age' => 'number|between:1,120',
  8. 'email' => 'email',
  9. ];
  10. protected $message = [
  11. 'name.require' => '名称必须',
  12. 'name.max' => '名称最多不能超过25个字符',
  13. 'age.number' => '年龄必须是数字',
  14. 'age.between' => '年龄只能在1-120之间',
  15. 'email' => '邮箱格式错误',
  16. ];
  17. protected $scene = [
  18. 'edit' => ['name','age'=>'require|number|between:1,120'],
  19. ];
  20. }

可以对场景设置一个回调方法,用于动态设置要验证的字段,例如:

  1. $rule = [
  2. 'name' => 'require|max:25',
  3. 'age' => 'number|between:1,120',
  4. 'email' => 'email',
  5. ];
  6. $msg = [
  7. 'name.require' => '名称必须',
  8. 'name.max' => '名称最多不能超过25个字符',
  9. 'age.number' => '年龄必须是数字',
  10. 'age.between' => '年龄只能在1-120之间',
  11. 'email' => '邮箱格式错误',
  12. ];
  13. $data = [
  14. 'name' => 'thinkphp',
  15. 'age' => 10,
  16. 'email' => 'thinkphp@qq.com',
  17. ];
  18. $validate = new Validate($rule);
  19. $validate->scene('edit', function($key,$data){
  20. return 'email'==$key && isset($data['id'])? true : false;
  21. });
  22. $result = $validate->scene('edit')->check($data);