验证器:在validate下创建一个验证器,按数据库表命名User
<?php namespace app\validate; use think\Validate; class User extends Validate { //验证规则 protected $rule = [ //require 必须的|min:5 'name'=> 'require|length:4,15', 'email' => 'email', 'password' => 'require|length:6,32', ]; //错误信息 protected $message = [ 'name.require' => '姓名不能为空', 'name.length' => '姓名必须在4-15个字符之间', 'email.email' => '必须为邮箱格式', 'password.require' => '密码不能为空', 'password.between' => '密码必须为6~32之间' ]; }
控制器:创建控制器Verify.php
<?php namespace app\index\controller; use think\Controller;//继承框架控制器 use app\validate\User;//导入验证器 use think\Validate; class Verify extends Controller { //验证器 public function demo1() { $data = [ 'name'=>'zas424', 'email'=>'1234@qq.com', 'password'=>'185434', ]; $validate = new User(); //实例化,获取验证对象 if(!$validate->check($data)){ //调用验证方法进行验证, dump($validate->getError());//返回错误信息 }else{ return '验证通过'; } } }