1、首先建立一个验证器类,并在验证器类中进行相关设置
实例
<?php namespace app\index\validate; use think\Validate; //此类为验证器类 继承框架的验证类 class Staff extends Validate{ //定义验证规则 protected $rule = [ "name" => "require|length:4,18", "age" => "require|between:18,60", "sex" => "in:0,1", "salary"=>"require|between:5000,8000" ]; //自定义错误信息提示 protected $message = [ "name.require" => "名称必须要填写", "name.length" => "名称长度必须在4到18位之间", "age.require" => "年龄必须填写", "age.between" => "年龄必须在18到60之间", "sex.in" => "性别必须是0和1", "salary.require" => "工资必须填写", "salary.between" => "工资必须在5000到8000之间", ]; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
2、在控制器中进行实例化验证器类
实例
<?php namespace app\index\controller; use app\index\validate\Staff; use think\Controller; class Validate extends Controller { //验证操作 public function index() { //1、验证器验证 //需要验证的数据 $data = [ "name" => "liyang", "age" => 45, "sex" => 0, "salary" => 6000 ]; $validate = new Staff(); //实例化验证器中的对象(注意) if (!$validate -> check($data)){ dump($validate -> getError()); //如果验证不通过 打印自定义的 错误信息 }else{ echo "验证通过"; } //使用继承的控制器中的验证方法验证 $data = [ "name" => "li", "age" => 45, "sex" => 0, "salary" => 6000 ]; //验证规则 $arr = 'app\index\validate\Staff'; //验证规则的类命名空间 $validate = $this -> validate($data,$arr); //验证通过返回true 验证不通过返回自定义错误信息 if ($validate !== true){ dump($validate); }else{ dump("验证通过了"); } //3、独立验证 $data = [ "name" => "liyang", "age" => 45, "sex" => 3, "salary" => 6000 ]; //定义验证规则 $rule = [ "name" => "require|length:4,18", "age" => "require|between:18,60", "sex" => "in:0,1", "salary"=>"require|between:5000,8000" ]; //自定义错误信息提示 $message = [ "name.require" => "名称必须要填写", "name.length" => "名称长度必须在4到18位之间", "age.require" => "年龄必须填写", "age.between" => "年龄必须在18到60之间", "sex.in" => "性别必须是0和1", "salary.require" => "工资必须填写", "salary.between" => "工资必须在5000到8000之间", ]; $validate = \think\Validate::make($rule,$message); if (!$validate ->check($data)){ dump($validate -> getError()); }else{ echo "验证通过"; } } }
运行实例 »
点击 "运行实例" 按钮查看在线实例