验证器:Phone.php
实例
<?php namespace app\validate; use think\Validate; class Phone extends Validate { //验证规则 protected $rule =[ 'name' => 'require|length:4,25', 'sex' => 'in:0,1', 'age' => 'require|between:16,60', 'number' => 'require|length:8,11' ]; //自定义错误信息 protected $message = [ 'name.require' => '姓名不能为空', 'name.length' => '长度字符在4-25个', 'sex.in' => '性别只能在在0和1之间选择', 'age.require' => '年龄不能为空', 'age.between' => '年龄只能在16-60岁', 'number.require' => '数字不能为空', 'number.length'=> '数字长度在8-11位' ]; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
控制器中进行调用:
实例
<?php namespace app\index\controller; use think\Controller; use app\validate\Phone; //导入验证器类 use think\Validate; class Verify extends Controller { //准备要验证的数据 public function demo1() { $data = [ 'name' => 'zhulao', 'age' =>20, 'sex' =>1, 'number' =>85475418 ]; $validate = new Phone(); if(!$validate->check($data)){ dump($validate->getError()); }else{ return '验证通过'; } } //验证器的简化:$this->validate($data,$rule,$message=[]) public function demo2() { //验证数据 $data = [ 'name' => 'zhulao', 'age' =>20, 'sex' =>1, 'number' =>85475418 ]; //验证规则 $rule = 'app\validate\Phone'; //进行验证 ,返回的是错误信息 $res = $this->validate($data,$rule); if($res !== true){ return $res; } return '验证通过'; } //如果是简单的验证可在控制器里完成验证的步骤,在当前的文档直接验证 public function demo3() { //验证数据 $data = ['name' => 'xiaoqin']; //验证规则 $rule = ['name' => 'require|length:4,20']; //错误信息 $message = ['name.require' => '姓名不能为空','name.length'=>'字符在4-20个']; $res = $this->validate($data,$rule,$message); if($res !== true){ return $res; } return '<h1 style="color:green">验证通过</h1>'; } //独立验证:直接实例化来完成 public function demo4() { //think\Validate //Validate::make():创建验证规则并返回验证对象 //$validate->check($data):验证 // 1.创建验证规则 $rule = ['age' => 'require|between:18,60']; //2.创建错误信息 $message = ['age.require' => '年龄不能为空哈','age.between' => '年龄只能在18-60岁']; //3.创建数据 $data = ['age' => 20]; //Validate::make()创建验证规则并返回验证对象 $validate = Validate::make($rule,$message); $res = $validate->check($data); echo $res ? '<h1 style="color:green">验证通过</h1>' : $validate->getError(); } }
运行实例 »
点击 "运行实例" 按钮查看在线实例