自定义laravel表单请求验证类(FormRequest共用一个rules()),一个文件搞定

首先创建Request

php artisan make:request CreateUserRequest

CreateUserRequest代码块



namespace App\Http\Requests;

use App\Http\Requests\Request;

class CreateUserRequest extends Request
{
        //验证规则
    protected $rules = [    
        'Student.userName' => 'required|between:2,4',
        'Student.userAge' => 'required|integer',
        'Student.userSex' => 'required|integer',
        'Student.addr' => 'required',
    ];
    //这里我只写了部分字段,可以定义全部字段
    protected $strings_key = [
        'Student.userName' => '用户名',
        'Student.userAge' => '年龄',
        'Student.userSex' => '性别',
        'Student.addr' => '地址',
    ];
    //这里我只写了部分情况,可以按需定义
    protected $strings_val = [
        'required'=> '为必填项',
        'min'=> '最小为:min',
        'max'=> '最大为:max',
        'between'=> '长度在:min和:max之间',
        'integer'=> '必须为整数',
        'sometimes'=> '',
    ];

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;//修改为true
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        $rules = $this->rules;
        // 根据不同的情况, 添加不同的验证规则
        if (Request::getPathInfo() == '/save')//如果是save方法
        {
            $rules['Student.addr'] = 'sometimes';
        }
        if (Request::getPathInfo() == '/edit')//如果是edit方法
        {
            $rules['Student.addr'] = 'required|min:5';
        }
        return $rules;        

    }

    public function messages(){
        $rules = $this->rules();
        $k_array = $this->strings_key;
        $v_array = $this->strings_val;
        foreach ($rules as $key => $value) {
            $new_arr = explode('|', $value);//分割成数组
            foreach ($new_arr as $k => $v) {
                $head = strstr($v,':',true);//截取:之前的字符串
                if ($head) {$v = $head;}
                $array[$key.'.'.$v] = $k_array[$key].$v_array[$v];                  
            }
        }
        return $array;
    }
}

控制器具体方法

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function save(\App\Http\Requests\CreateUserRequest $request)
    {
            //这里会自动调用表单验证
            //验证成功后继续向下执行
            $data = $request->input('Student');
            if(User::create($data)){
               return redirect('/')->with('success', '添加成功!');
            }else{
               return redirect('/create')->with('error', '添加失败!'); 
            }
    }

对应的模板文件

<form class="form-horizontal" method="post" action="save">
    <div class="form-group">
        <label for="name" class="col-sm-2 control-label">姓名label>
        {!! csrf_field() !!}
        <div class="col-sm-5">
            <input type="text" class="form-control" id="name" name="Student[userName]" placeholder="请输入学生姓名" value="{{ old('Student')['userName']}}">
        div>
        <div class="col-sm-5">
            <p class="form-control-static text-danger">{{ $errors->first('Student.userName') }}p>
        div>
    div>
    <div class="form-group">
        <label for="age" class="col-sm-2 control-label">年龄label>

        <div class="col-sm-5">
            <input type="text" class="form-control" id="age" name="Student[userAge]" placeholder="请输入学生年龄" value="{{ old('Student')['userAge']}}">
        div>
        <div class="col-sm-5">
            <p class="form-control-static text-danger">{{$errors->first('Student.userAge')}}p>
        div>
    div>
    <div class="form-group">
        <label for="age" class="col-sm-2 control-label">地址label>

        <div class="col-sm-5">
            <input type="text" class="form-control" id="addr" name="Student[addr]" placeholder="请输地址" >
        div>
        <div class="col-sm-5">
            <p class="form-control-static text-danger">{{$errors->first('Student.addr')}}p>
        div>
    div>                        
    <div class="form-group">
        <label class="col-sm-2 control-label">性别label>

        <div class="col-sm-5">
            <label class="radio-inline">
                <input type="radio" name="Student[userSex]" value="1" > 未知
            label>
            <label class="radio-inline">
                <input type="radio" name="Student[userSex]" value="2">label>
            <label class="radio-inline">
                <input type="radio" name="Student[userSex]" value="3">label>
        div>
        <div class="col-sm-5">
            <p class="form-control-static text-danger">{{ $errors->first('Student.userSex') }}p>
        div>
    div>
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-primary">提交button>
        div>
    div>
form>

效果展示


自定义laravel表单请求验证类(FormRequest共用一个rules()),一个文件搞定_第1张图片


写在最后


通过文本可以看到, Form Requests 对于简化表单请求的数据校验是非常强大和方便的.这里我做了一些修改,使得rules()能够可复用且只新增一个Request。如果有更好的解决方法,欢迎留言。

你可能感兴趣的:(laravel,php)