1、自定义验证类验证
实例
<?php namespace app\index\controller; use app\index\model\Staff as StaffModel; use think\Controller; use think\db\Query; use app\index\validate\Staff as StaffValidate; /** * Created by PhpStorm. * User: lenovo * Date: 2019/3/23 * Time: 10:34 */ class Staff extends Controller { //验证器:类,使用户自定义的验证类 public function demo5(){ //用数组模拟表单提交过来的数据 $data = [ 'name'=> 'guoer', 'sex' => '0', 'age'=> '25', 'email'=>'sajkd@163.com' ]; $validate = new StaffValidate(); $result = $validate->check($data); if(false === $result){ halt($validate->getError()); } return '验证通过'; } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
<?php //用户自定义的验证器类,用来对staff表中的字段进行验证 namespace app\index\validate; use think\Validate; /** * Created by PhpStorm. * User: lenovo * Date: 2019/3/26 * Time: 8:49 */ class Staff extends Validate { //属性来设置 //1.给数据表中的字段绑定验证规则 protected $rule = [ 'name' => 'require|chsAlpha|length:2,20', 'sex' =>'require|integer|in:0,1', 'age' => 'require|integer|between:18,59', 'email' => 'require|email' ]; //2、验证提示 protected $message = [ 'name.require'=> '姓名不能为空', 'name.chsAlpha'=>'姓名必须为字母或汉字', 'name.length' => '姓名长度必须在3到20个字符之间', 'sex.require'=> '性别不能为空', 'sex.integer'=> '性别必须是整数', 'sex.in' => '性别必须是0或1', 'age.require'=> '年龄不能为空', 'age.integer'=> '年龄必须是整数', 'age.between' => '年龄必须在18到59之间', 'email.require' => '邮箱不能为空', 'email.email' => '邮箱格式不对', ]; //验证场景(可选) protected $scene = [ 'add' => ['name','sex','email'], 'update' =>['name','sex'], ]; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
2、独立验证
实例
<?php namespace app\index\controller; use app\index\model\Staff as StaffModel; use think\Controller; use think\db\Query; use app\index\validate\Staff as StaffValidate; use think\Validate; /** * Created by PhpStorm. * User: lenovo * Date: 2019/3/23 * Time: 10:34 */ class Staff extends Controller { //验证器:类,使用户自定义的验证类 public function demo5(){ //用数组模拟表单提交过来的数据 $data = [ 'name'=> 'guoer', 'sex' => '0', 'age'=> '25', 'email'=>'sajkd@163.com' ]; $validate = new StaffValidate(); $result = $validate->check($data); if(false === $result){ halt($validate->getError()); } return '验证通过'; } //独立验证 public function demo6() { //think\validate //1、创建验证规则 $rule = [ 'name' => 'require|chsAlpha|length:2,20', 'sex' => 'require|integer|in:0,1', 'age' => 'require|integer|between:18,59', 'email' => 'require|email' ]; //验证提示 $message = [ 'name.require' => '姓名不能为空', 'name.chsAlpha' => '姓名必须为字母或汉字', 'name.length' => '姓名长度必须在3到20个字符之间', 'sex.require' => '性别不能为空', 'sex.integer' => '性别必须是整数', 'sex.in' => '性别必须是0或1', 'age.require' => '年龄不能为空', 'age.integer' => '年龄必须是整数', 'age.between' => '年龄必须在18到59之间', 'email.require' => '邮箱不能为空', 'email.email' => '邮箱格式不对', ]; //用数组模拟表单提交过来的数据 $validate = Validate::make($rule, $message); $data = [ 'name' => 'guoer', 'sex' => '0', 'age' => '25', 'email' => 'sajkd@163.com' ]; $result = $validate->check($data); if(false === $result){ halt($validate->getError()); } return '验证通过'; } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
3、