天天看點

Laravel技巧集錦(六):使用validate驗證表單資料

1、控制器中

public function add(){
        


        //validate 驗證


        $rules = [
            'title'=>'required|string|max:100|min:5',
            'content'=>'required|min:10'
        ];

        $message = [
            'title.min'=>'文章标題至少5個字元', //  use this method or use lang(zh)
        ];


        $this->validate(\request(),$rules,$message);

        //logic 邏輯
        Post::create(\request(['title','content']));

        //render 渲染
        return redirect('/posts');
    }      

2、在view中顯示錯誤資訊

@if(count($errors)>0)
     @foreach($errors->all() as $error)
           <div class="alert alert-danger" role="alert">
                           {{$error}}
           </div>
     @endforeach
@endif      

3、設定為zh(config\App.php)

//'fallback_locale' => 'en',
'fallback_locale' => 'zh',      

【非必須】4、将錯誤資訊提示改成中文,(resources\lang\zh\validation.php)

<?php

return [

    'accepted'             => ':attribute必須接受',
    'active_url'           => ':attribute必須是一個合法的 URL',
    'after'                => ':attribute 必須是 :date 之後的一個日期',
    'after_or_equal'       => ':attribute 必須是 :date 之後或相同的一個日期',
    'alpha'                => ':attribute隻能包含字母',
    'alpha_dash'           => ':attribute隻能包含字母、數字、中劃線或下劃線',
    'alpha_num'            => ':attribute隻能包含字母和數字',
    'array'                => ':attribute必須是一個數組',
    'before'               => ':attribute 必須是 :date 之前的一個日期',
    'before_or_equal'      => ':attribute 必須是 :date 之前或相同的一個日期',
    'between'              => [
        'numeric' => ':attribute 必須在 :min 到 :max 之間',
        'file'    => ':attribute 必須在 :min 到 :max KB 之間',
        'string'  => ':attribute 必須在 :min 到 :max 個字元之間',
        'array'   => ':attribute 必須在 :min 到 :max 項之間',
    ],
    'boolean'              => ':attribute 字元必須是 true 或 false',
    'confirmed'            => ':attribute 二次确認不比對',
    'date'                 => ':attribute 必須是一個合法的日期',
    'date_format'          => ':attribute 與給定的格式 :format 不符合',
    'different'            => ':attribute 必須不同于 :other',
    'digits'               => ':attribute必須是 :digits 位.',
    'digits_between'       => ':attribute 必須在 :min 和 :max 位之間',
    'dimensions'           => ':attribute具有無效的圖檔尺寸',
    'distinct'             => ':attribute字段具有重複值',
    'email'                => ':attribute必須是一個合法的電子郵件位址',
    'exists'               => '標明的 :attribute 是無效的.',
    'file'                 => ':attribute必須是一個檔案',
    'filled'               => ':attribute的字段是必填的',
    'image'                => ':attribute必須是 jpeg, png, bmp 或者 gif 格式的圖檔',
    'in'                   => '標明的 :attribute 是無效的',
    'in_array'             => ':attribute 字段不存在于 :other',
    'integer'              => ':attribute 必須是個整數',
    'ip'                   => ':attribute必須是一個合法的 IP 位址。',
    'json'                 => ':attribute必須是一個合法的 JSON 字元串',
    'max'                  => [
        'numeric' => ':attribute 的最大長度為 :max 位',
        'file'    => ':attribute 的最大為 :max',
        'string'  => ':attribute 的最大長度為 :max 字元',
        'array'   => ':attribute 的最大個數為 :max 個.',
    ],
    'mimes'                => ':attribute 的檔案類型必須是 :values',
    'min'                  => [
        'numeric' => ':attribute 的最小長度為 :min 位',
        'file'    => ':attribute 大小至少為 :min KB',
        'string'  => ':attribute 的最小長度為 :min 字元',
        'array'   => ':attribute 至少有 :min 項',
    ],
    'not_in'               => '標明的 :attribute 是無效的',
    'numeric'              => ':attribute 必須是數字',
    'present'              => ':attribute 字段必須存在',
    'regex'                => ':attribute 格式是無效的',
    'required'             => ':attribute 字段是必須的',
    'required_if'          => ':attribute 字段是必須的當 :other 是 :value',
    'required_unless'      => ':attribute 字段是必須的,除非 :other 是在 :values 中',
    'required_with'        => ':attribute 字段是必須的當 :values 是存在的',
    'required_with_all'    => ':attribute 字段是必須的當 :values 是存在的',
    'required_without'     => ':attribute 字段是必須的當 :values 是不存在的',
    'required_without_all' => ':attribute 字段是必須的當 沒有一個 :values 是存在的',
    'same'                 => ':attribute和:other必須比對',
    'size'                 => [
        'numeric' => ':attribute 必須是 :size 位',
        'file'    => ':attribute 必須是 :size KB',
        'string'  => ':attribute 必須是 :size 個字元',
        'array'   => ':attribute 必須包括 :size 項',
    ],
    'string'               => ':attribute 必須是一個字元串',
    'timezone'             => ':attribute 必須是個有效的時區.',
    'unique'               => ':attribute 已存在',
    'url'                  => ':attribute 無效的格式',

    /*
    |--------------------------------------------------------------------------
    | Custom Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | Here you may specify custom validation messages for attributes using the
    | convention "attribute.rule" to name the lines. This makes it quick to
    | specify a specific custom language line for a given attribute rule.
    |
    */

    'custom' => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
        ],
    ],

  

    'attributes' => [
        // 'name'         => '名字',
        // 'age'         => '年齡',
    ],

];      

補充:實際開發中,我們常常需要精簡控制器代碼,這樣看起來邏輯清楚,一目了然。是以可以将驗證規則提出來(依賴注入)。

步驟:

1、生成檔案,位于app\Http\Requests\StoreQuestionRequest.php

php artisan make:request StoreQuestionRequest      
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreQuestionRequest extends FormRequest
{

    public function authorize()
    {
        return true;//true驗證
    }

 
    public function rules()
    {
        return [
            'title'=>'required|min:6|max:196',  
        ];
    }
    
    public function messages()
    {
        return [
            'title.required'=>'标題不能為空',
        ]; 
    }
}      
public function store(StoreQuestionRequest $request)
    {
        $data = [
            'title'=>$request->get('title'),
        ];
        Question::create($data);
        return ;
    }