企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[验证 · ThinkPHP5.0完全开发手册 · 看云 (kancloud.cn)](https://www.kancloud.cn/manual/thinkphp5/129319) [验证器 · ThinkPHP6.0完全开发手册 · 看云 (kancloud.cn)](https://www.kancloud.cn/manual/thinkphp6_0/1037624) [TOC] [Tp-validate进阶thinkphp](https://www.cnblogs.com/lichihua/p/9697354.html) ## **验证规则** ~~~ $rule = [ 'name|姓名' => 'require|max:25', 'age' => 'number|between:1,120', 'email' => 'email', ]; //或者 $rule = [ 'name' => ['require', 'max' => 25, 'regex' => '/^[\w|\d]\w+/'], 'age|年龄' => ['number', 'between' => '1,120'], 'email' => 'email', ]; //或者方法定义 $validate = \think\facade\Validate::rule('age', 'number|between:1,120') ->rule([ 'name' => 'require|max:25', 'email' => 'email' ]); $rule = [ ['name','require|max:25','名称必须|名称最多不能超过25个字符'], ['age','number|between:1,120','年龄必须是数字|年龄必须在1~120之间'], ['email','email','邮箱格式错误'] ]; ~~~ >[danger]`|`两边不能有空格如:**require |max:25**就会报错 ## **独立验证** ``` $postdata=[ 'name'=>'dash', 'age'=>'20', 'email'=>'xxx.qq.com', 'mobile'=>'13599997078', ]; $rule = [ 'name' => ['require', 'max' => 25, 'regex' => '/^[\w|\d]\w+/'], 'age|年龄' => ['number', 'between' => '1,120'], 'email' => 'email', ]; //实例化并传入规则 //$validate=new Validate($rule);//tp5的用法 $validate = \think\facade\Validate::rule($rule); //开始验证 $result=$validate ->batch()->check($postdata); $validate->getError(); ``` ## **验证器** ``` class AccountEquipmentType extends Validate { protected $rule = [ 'status|状态' => [ 'require' => 'require', 'max' => '1', ], 'account_name|出账类型' => [ 'require' => 'require', ] ]; } //控制器执行验证: $postdata=[ 'name'=>'dash', 'age'=>'20', 'email'=>'xxx.qq.com', 'mobile'=>'13599997078', ]; //实例化 $validate = new AccountEquipmentType (); //开始验证 $result=$validate ->batch()->check($postdata); //拆开 $v = new AccountEquipmentType (); $v->rule($validate); $v->message($message); $v->batch(true); $result = $v->failException(false)->check($postdata); if (true !== $result) { return $v->getError(); } else { return $result; } ``` ## **自定义验证规则** 一般会新建个基础验证器继承Validate里面放自定义验证规则 然后每个模块的验证器继承与基础验证器,定义rule 属性 控制器在实例化模块验证器并验证 ``` namespace app\api\validate; use think\Request; use think\Validate; /** * Class BaseValidate * 验证类的基类 */ class BaseValidate extends Validate { protected $rule = [ 'name' => 'require|isNotEmpty', 'mobile' => 'require|isMobile', ]; protected $message = [ 'name.require' => '名称必须', 'name.isNotEmpty' => '名称不能为空', 'mobile.isMobile' => '手机格式不正确', 'age.between' => '年龄只能在1-120之间', 'email' => '邮箱格式错误', ]; protected function isNotEmpty($value, $rule='', $data='', $field='') { if (empty($value)) { return $field . '不允许为空'; } else { return true; } } //手机号的验证规则 protected function isMobile($value) { $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^'; $result = preg_match($rule, $value); if ($result) { return true; } else { return false; } } } //控制器验证 //实例化 $validate = new BaseValidate(); //开始验证 $result=$validate ->batch()->check($postdata); ```