laravel
框架中默認(rèn)的validate
驗(yàn)證,在處理錯(cuò)誤的時(shí)候,默認(rèn)是返回上一頁,當(dāng)為ajax
的時(shí)候才會(huì)返回Json
。如果我們要一直返回Json
的話,那么需要重寫錯(cuò)誤處理
如下:在Requests
目錄只用 新建BaseRequest
類
代碼如下
<?php /** * @文件名稱: BaseRequest.php. * @author: daisc * @email: [email protected] * @Date: 2019/1/8 */ namespace App\Http\Requests\Front; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\Exceptions\HttpResponseException; class BaseRequest extends FormRequest { public function failedValidation($validator) { $error= $validator->errors()->all(); // $error = $validator; throw new HttpResponseException(response()->json(['code'=>1,'message'=>$error[0]])); } }
重寫了failedValidation
方法,將拋出錯(cuò)誤處理為了json
格式的。
然后在自定義的處理驗(yàn)證類中,繼承該類就行了,
如:RegisterForm
中
<?php namespace App\Http\Requests\Front; class RegisterForm extends BaseRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'phone'=>'required|regex:"^1\d{10}"', 'email' => 'required|email', 'password'=>'required|confirmed' ]; } public function messages() { return [ 'phone.required'=>'手機(jī)號(hào)不能為空', 'phone.regex'=>'請輸入正確的手機(jī)號(hào)', ]; } }
當(dāng)我們在控制器中調(diào)用RegisterForm
的時(shí)候,就回返回Json
格式的錯(cuò)誤信息。
不分是否是AJAX
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。