ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
用法一:控制器中自定义验证 ``` //验证规则 $rule = [ 'title|标题'=>'require', 'keys|关键字'=>'require', 'content|内容'=>'require', ]; //$data是需要验证的数据 $row = $this->validate($data,$rule); //验证不通过,返回错误信息 if ($row !==true){ $this->error($row); } ``` 用法二:场景验证:在app目录下建一个validate文件夹,再建一个类文件(文件名和模型一致) ``` 1.验证类文件: namespace app\validate; use think\Validate; //继承验证类 class User extends Validate { //定义验证规则 protected $rule = [ 'username|用户名'=>'require|min:1|max:20', 'password|密码'=>'require|length:6,12', 'repassword|确认密码'=>'require|confirm:password', 'email|邮箱'=>'require|email', 'code|验证码'=>'require|captcha', ]; //中文提示消息,unique:判断这个字段是否存在重复 protected $message = [ 'username.unique' => '用户名已存在', 'email.uinque' => '邮箱已经存在', 'password.length:6,20' => '密码必须在6到20位', ]; // 注册验证场景定义,scene+场景名 public function sceneAdd(){ return $this->only(['username','password','repassword','email'])->append('username','unique:user')->append('email','unique:user'); } // 登录验证场景定义 public function sceneLogin() { return $this->only(['username', 'password', 'code']); } public function sceneEdit() { return $this->only(['username','email'])->append('password','length:6,20'); } public function sceneForget() { return $this->only(["email","password","repassword"]); } } 2.在控制器中使用 先引入:use app\validate\User as UserValidate; // 实例化验证器 $validate = new UserValidate(); // 判断验证失败返回错误信息,使用添加场景edit验证 if (!$validate->scene("edit")->check($data)){ $msg = $validate->getError(); $this->error($msg); } ```