自定义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

原文地址:https://www.cnblogs.com/vickystudy/p/11443630.html

时间: 2024-07-31 20:52:14

自定义laravel表单请求验证类(FormRequest共用一个rules())的相关文章

Laravel 5.5 FormRequest 自定义表单请求验证类

1.把表单验证逻辑写在Controller中,这是最基础的方法,但是不好维护,如: 1 namespace App\Http\Controllers\Admin; 2 3 use Illuminate\Http\Request; 4 use App\Http\Controllers\Controller; 5 6 class MemberController extends Controller 7 { 8 // 登录模块 9 public function login (Request $re

看用Tornado如何自定义实现表单验证

我们知道,平时在登陆某个网站或软件时,网站对于你输入的内容是有要求的,并且会对你输入的错误内容有提示,对于Django这种大而全的web框架,是提供了form表单验证功能,但是对于Tornado而言,就没有这功能,所以就需要我们来自己自定义form表单验证,而且这种方法正是Django里的form表单验证的实质内容,也帮我们在后面学习Django理解相关的源码. 写之前,我们必须知道form表单验证的实质是什么? 实质就是正则匹配 我们知道用户提交数据是通过post方式提交,所以我们重写post

iview自定义表单验证 &amp;&amp;&amp; 多表单同时验证

一.自定义验证     data () { const validateSectionFileType = (rule, value, callback) => { if (value <= 0) { callback(new Error('类型不能为空')); } else { callback(); } }; const validateSectionTime = (rule, value, callback) => { if (value === '') { callback(ne

利用 ajax自定义Form表单的请求方式

需求场景:有时候单纯的form表单无法向后端传递额外的参数 比如需要action传递js异步生成的参数 ,form表单默认的action就无法满足需求,这时就需要我们自定义form表单的提交方式. html:(向后台传递对任务的评论内容,默认缺点:不能携带任务id) 1 <div> 2 <form action="#" id="form_comment"> 3 <textarea id="comment" requi

Thinkphp表单自动验证

之前项目经常用到,没做总结. 自动验证是Thinphp模型层提供的一种数据验证方法,可以在使用create创建数据对象的时候自动进行数据验证. 原理: create()方法收集表单($_POST)信息并返回,同时触发表单自动验证,过滤非法字段, 在控制器中使用create()方法,(返回值为true/false),会自动触发模型类中的$_validate属性(为父类Model中的方法,在子类Model中重写),在$_validate中自定义验证规则(验证规则下面会详细说明),当create()方

thinkPHP 表单自动验证功能

昨天晚上我们老大叫我弄表单自动验证功能,愁了半天借鉴了好多官网的知识,才出来,诶,总之分享一下我自己的成果吧! thinkphp 在Model基类为我们定义了自动验证的函数和正则表达式,我们只需要在对应的数据库表的模型类下建立$_validate属性就可以了. 1.我们找到Model基类,可以看到 protected $_validate       = array();  // 自动验证定,它是数组类型的,下面在对应数据模型文件定义它: 2. public function CheckVeri

Spring Security 4 自定义登录表单 注解和XML例子(带源码)

上一篇文章: Spring Security 4 Hello World 基于注解 和 XML 例子 下一篇:Spring Security 4 退出 示例 原文地址:http://websystique.com/spring-security/spring-security-4-custom-login-form-annotation-example/ [已翻译文章,点击分类里面的spring security 4查看.] [ 翻译by 明明如月 QQ 605283073] 本文演示Sprin

AngularJS实现表单手动验证和表单自动验证

AngularJS的表单验证大致有两种,一种是手动验证,一种是自动验证.一.手动验证 所谓手动验证是通过AngularJS表单的属性来验证.而成为AngularJS表单必须满足两个条件: 1.给form元素加上novalidate="novalidate": 2.给form元素加上name="theForm",如下: <!DOCTYPE html> <html lang="en" ng-app="myApp1"

MVC扩展ModelBinder,通过继承DefaultModelBinder把表单数据封装成类作为action参数

把视图省.市.街道表单数据,封装成一个类,作为action参数.如下: action方法参数类型: namespace MvcApplication1.Models{    public class Customer    {        public string Address { get; set; }    }} 在自定义ModelBinder中,接收视图表单数据,封装成Customer类. using System.Web; using System.Web.Mvc; using M