自定義laravel表單請求驗證類(FormRequest共用一個rules())


我們可以利用Form Request來封裝表單驗證代碼,從而精簡Controller中的代碼邏輯,使其專注於業務。而獨立出去的表單驗證邏輯可以復用到其它請求中,看過幾篇文章,大多都是講怎么創建Request,表面看起來是將邏輯與業務分離了,但是沒有做到復用,一個業務就得新建一個Request類實在太累,索性這里我將項目全部的表單驗證放在一個Request類里,實現高度可復用,下面是具體實現。

首先創建Request

php artisan make:request CreateUserRequest

CreateUserRequest代碼塊 

 1 <?php
 2 
 3 namespace App\Http\Requests;
 4 
 5 use App\Http\Requests\Request;
 6 
 7 class CreateUserRequest extends Request
 8 {
 9         //驗證規則可自己添加需要驗證的字段
10     protected $rules = [    
11         'Student.userName' => 'required|between:2,4',
12         'Student.userAge' => 'required|integer',
13         'Student.userSex' => 'required|integer',
14         'Student.addr' => 'required',
15     ];
16     //這里我只寫了部分字段,可以定義全部字段
17     protected $strings_key = [
18         'Student.userName' => '用戶名',
19         'Student.userAge' => '年齡',
20         'Student.userSex' => '性別',
21         'Student.addr' => '地址',
22     ];
23     //這里我只寫了部分情況,可以按需定義
24     protected $strings_val = [
25         'required'=> '為必填項',
26         'min'=> '最小為:min',
27         'max'=> '最大為:max',
28         'between'=> '長度在:min和:max之間',
29         'integer'=> '必須為整數',
30         'sometimes'=> '',
31     ];
32 
33     /**
34      * Determine if the user is authorized to make this request.
35      *
36      * @return bool
37      */
38     public function authorize()
39     {
40         return true;//修改為true
41     }
42 
43     /**
44      * Get the validation rules that apply to the request.
45      *
46      * @return array
47      */
48     public function rules()
49     {
50 
51         $rules = $this->rules;
52         // 根據不同的情況, 添加不同的驗證規則
53         if (Request::getPathInfo() == '/save')//如果是save方法
54         {
55             $rules['Student.addr'] = 'sometimes';
56         }
57         if (Request::getPathInfo() == '/edit')//如果是edit方法
58         {
59             $rules['Student.addr'] = 'required|min:5';
60         }
61         return $rules;        
62 
63     }
64   //返回給前台的錯誤信息
65     public function messages(){
66         $rules = $this->rules();
67         $k_array = $this->strings_key;
68         $v_array = $this->strings_val;
69         foreach ($rules as $key => $value) {
70             $new_arr = explode('|', $value);//分割成數組
71             foreach ($new_arr as $k => $v) {
72                 $head = strstr($v,':',true);//截取:之前的字符串
73                 if ($head) {$v = $head;}
74                 $array[$key.'.'.$v] = $k_array[$key].$v_array[$v];                  
75             }
76         }
77         return $array;
78     }
79 }

控制器具體方法

 1     /**
 2      * Show the form for creating a new resource.
 3      *
 4      * @return \Illuminate\Http\Response
 5      */
 6     public function save(\App\Http\Requests\CreateUserRequest $request)
 7     {
 8             //這里會自動調用表單驗證
 9             //驗證成功后繼續向下執行
10             $data = $request->input('Student');
11             if(User::create($data)){
12                return redirect('/')->with('success', '添加成功!');
13             }else{
14                return redirect('/create')->with('error', '添加失敗!'); 
15             }
16     }

對應的模板文件

 1 <form class="form-horizontal" method="post" action="save">
 2     <div class="form-group">
 3         <label for="name" class="col-sm-2 control-label">姓名</label>
 4         {!! csrf_field() !!}
 5         <div class="col-sm-5">
 6             <input type="text" class="form-control" id="name" name="Student[userName]" placeholder="請輸入學生姓名" value="{{ old('Student')['userName']}}">
 7         </div>
 8         <div class="col-sm-5">
 9             <p class="form-control-static text-danger">{{ $errors->first('Student.userName') }}</p>
10         </div>
11     </div>
12     <div class="form-group">
13         <label for="age" class="col-sm-2 control-label">年齡</label>
14 
15         <div class="col-sm-5">
16             <input type="text" class="form-control" id="age" name="Student[userAge]" placeholder="請輸入學生年齡" value="{{ old('Student')['userAge']}}">
17         </div>
18         <div class="col-sm-5">
19             <p class="form-control-static text-danger">{{$errors->first('Student.userAge')}}</p>
20         </div>
21     </div>
22     <div class="form-group">
23         <label for="age" class="col-sm-2 control-label">地址</label>
24 
25         <div class="col-sm-5">
26             <input type="text" class="form-control" id="addr" name="Student[addr]" placeholder="請輸地址" >
27         </div>
28         <div class="col-sm-5">
29             <p class="form-control-static text-danger">{{$errors->first('Student.addr')}}</p>
30         </div>
31     </div>                        
32     <div class="form-group">
33         <label class="col-sm-2 control-label">性別</label>
34 
35         <div class="col-sm-5">
36             <label class="radio-inline">
37                 <input type="radio" name="Student[userSex]" value="1" > 未知
38             </label>
39             <label class="radio-inline">
40                 <input type="radio" name="Student[userSex]" value="2">41             </label>
42 ![QQ截圖20170613152555.png](http://upload-images.jianshu.io/upload_images/2825702-f008b65789a425f4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
43 
44             <label class="radio-inline">
45                 <input type="radio" name="Student[userSex]" value="3">46             </label>
47         </div>
48         <div class="col-sm-5">
49             <p class="form-control-static text-danger">{{ $errors->first('Student.userSex') }}</p>
50         </div>
51     </div>
52     <div class="form-group">
53         <div class="col-sm-offset-2 col-sm-10">
54             <button type="submit" class="btn btn-primary">提交</button>
55         </div>
56     </div>
57 </form>

效果展示

 

 

 

 

寫在最后


通過文本可以看到, Form Requests 對於簡化表單請求的數據校驗是非常強大和方便的.這里我做了一些修改,使得rules()能夠可復用且只新增一個Request。如果有更好的解決方法,歡迎留言。

轉載:https://www.jianshu.com/p/0225e63454e8

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM