验证器:
实例
<?php namespace app\validate; use think\Validate; class Staff0525 extends Validate { //验证规则 protected $rule = [ 'name' => 'require|length:2,10', 'age' => 'require|between:10,50', 'height' => 'gt:100' ]; //自定义错误信息 protected $message = [ 'name.require' => '员工姓名不能为空', 'name.length' => '姓名必须在2到10个字符之间', 'age.require' => '年龄不能为空', 'age.between' => '年龄必须在10到50之间', 'height.gt' => '身高必须大于100' ]; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
在控制器中调用:
实例
<?php namespace app\index\controller; use think\Controller; use app\validate\Staff0525; use think\Validate; class Homework0525 extends Controller { //验证器 public function demo1() { //要验证的数据 $data = [ 'name' => 'xiaoming', 'age' => 25, 'height' => 180 ]; $validate = new Staff0525(); if (!$validate->check($data)) { dump($validate->getError()); } else { return '验证通过'; } } //验证器的简化: $this->validate($data, $rule, $mess) public function demo2() { //第一种 // $data = [ // 'name' => 'xiaoming', // 'age' => 25, // 'height' => 180 // ]; // $rule = 'app\validate\Staff0525'; // $res = $this->validate($data, $rule); //第二种 $data = ['age' => 25]; $rule = ['age' => 'between:10,50']; $mess = ['age.between' => '年龄必须在10到50之间']; $res = $this->validate($data, $rule, $mess); if (true !== $res) { return $res; } return '验证成功'; } //独立验证 public function demo3() { //1.创建验证规则 $rule = ['age' => 'between:10,50']; //2.创建错误信息 $mess = ['age.between' => '年龄必须在10到50之间']; //3.创建数据 $data = ['age' => 25]; //Validate::make():创建验证规则并返回验证对象 $validate = Validate::make($rule, $mess); $res = $validate->check($data); return $res ? '验证通过' : $validate->getError(); } }
运行实例 »
点击 "运行实例" 按钮查看在线实例