表单验证

表单验证

基于 laravel 的验证器扩展了自动验证与场景支持。

  • 验证类库 app/Http/Validate/Validate.php
    <?php
    namespace App\Http\Validate;
    use Illuminate\Support\Facades\Validator;
    class Validate {
        //当前场景
        protected $scene = null;
        //错误信息
        protected $error = null;
        //验证规则
        protected function rule(){
            return [];
        }
        //提示信息
        protected function message(){
            return [];
        }
        //场景规则
        protected function rules(){
            return [];
        }
        //设置场景
        public function scene($name){
            $this->scene = $name;
            return $this;
        }
        //数据验证
        public function check($data,$rule=[],$message=[],$rules=[]){
            //...
        }
        // 获取错误信息
        public function getError(){
            return $this->error;
        }
    }
    
    
  • 示例代码
    1. 验证规则 app/Http/Validate/Login.php
      <?php
      namespace App\Http\Validate;
      use Illuminate\Http\Request;
      use Illuminate\Support\{Str,Arr};
      use Illuminate\Validation\Rule;
      class Login extends Validate {
          public $validate;
          public $controller;
          public function __construct(Request $request){
              //控制器规则
              $this->validate=[
                  'check'=>[
                      'rule'=>[
                          'user' => ['required'],
                          'pwd' => ['required']
                      ],
                      'message'=>[
                          'user.required' => '用户名不可为空',
                          'pwd.required' => '密码不可为空'
                      ]
                  ]
              ];
              //获取控制器
              $this->controller=Str::after($request->route()->getActionName(),'@');
          }
          //验证规则
          public function rule(){
              $rule=Arr::get($this->validate,$this->controller.'.rule',[]);
              return $rule;
          }
          //提示信息
          public function message(){
              $message=Arr::get($this->validate,$this->controller.'.message',[]);
              return $message;
          }
          //场景规则
          public function rules(){
              $rules=Arr::get($this->validate,$this->controller.'.rules',[]);
              return $rules;
          }
      }
      
    2. 数据验证
      <?php
      namespace App\Http\Controllers;
      use Illuminate\Http\Request
      use App\Http\Validate\Login as Validate;
      class Login extends Controller {
          //登录验证
          public function check(Request $request,Validate $validate){
              $input=$request->input();
              $verify=$validate->check($input);
              if($verify){
                  //验证成功
              }else{
                  //验证失败
              	$err=$validate->getError();
              }
          }
      }
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
搜索