ThinkPhp5.1的验证器和独立验证
静态代理
<?php namespace app\facade; use think\facade; class User extends Facade { protected static function getFacadeClass() { return 'app\validate\User'; } }
验证器类继承自Validate类,主要作用初始化rule
<?php namespace app\validate; use think\Validate; class User extends Validate { protected $rule=[ 'name|姓名'=>[ 'require', 'min'=>2, 'max'=>20, ], 'email'=>[ 'require', 'email', ], 'password'=>[ 'require', 'alphaNum', ], 'mobile'=>[ 'require', 'mobile', ], ]; }
控制器类
<?php namespace app\index\controller; //use app\validate\User; use app\facade\User; use think\Controller; use think\facade\Validate; class Demo9 extends Controller { public function test1() { $date=[ 'name'=>'好好好好好', 'email'=>'hhhhh@php.cn', 'password'=>'123abc', 'mobile'=>'18357636217' ]; //自定义验证器类验证。 // $validate=new User; // if (!$validate->check($data)){ // return $validate->getError(); // } // return '通过验证'; //静态代理验证 if (!User::check($date)){ return User::getError(); } return '通过验证'; } //控制器内定验证方法验证 public function test2() { $validate='app\validate\User'; $date=[ 'name'=>'好好好好好', 'email'=>'hhhhh@php.cn', 'password'=>'123abc', 'mobile'=>'18357636217' ]; $res=$this->validate($date,$validate); if (true!==$res){ return $res; } return '通过验证'; } //独立验证器 public function test3() { $rule = [ 'name|姓名' => [ 'require', 'min' => 2, 'max' => 20, ], 'email' => [ 'require', 'email', ], 'password' => [ 'require', 'alphaNum', ], 'mobile' => [ 'require', 'mobile', ], ]; $date = [ 'name' => '好好好好好', 'email' => 'hhhhh@php.cn', 'password' => '123abc', 'mobile' => '18357636217' ]; Validate::rule($rule); if (Validate::check($date)) { return '验证通过'; } else { return Validate::getError(); } } }