Laravel表單驗證,攔截ajax,自定義返回資料
阿新 • • 發佈:2019-02-10
第一步:找到app\Http\Requests\Requests
類,並在類中新增以下方法
protected function failedValidation(Validator $validator)
{
throw new ValidationException($validator,$this->response(
$this->formatErrors($validator)));
}
public function response(array $errors)
{
if (($this->ajax() && ! $this->pjax()) || $this->wantsJson()) {
$errorsmsg = [];
foreach($errors as $k => $v){
$errorsmsg[$k] = $v[0];
}
return new JsonResponse($errorsmsg, 200);//更改格式,以及定義返回狀態值
}
return $this ->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
以上程式碼修改好後,在前端模擬ajax請求,表單驗證失敗後,返回的格式應該就是我們更改之後的格式。