Laravel 5.5 FormRequest 自定义错误消息

  使用FormRequest进行表单验证,就不用让验证逻辑和控制器里面的逻辑都混在一起。但在使用的时候呢,发现json错误返回的数据,与我们想要的有点差距。下面我给个例子:(不喜勿喷)
  

  在用ajax进行提交时,如果验证错了,那么他会返回
  
  
  如果是权限错了,他会返回
  

  但我想要的是
  

  那怎么办呢,其实很简单
  我们只需要在 App\Exceptions\Handler 里面重写两个函数就可以了
  
  添加上这两个函数,然后里面怎么定义,就看你了
  记得加上
  

       use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;

最后附上这两个文件的代码
LoginPost

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Auth\AuthenticationException; class LoginPost extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(){
if($this->input('account')=='aaa@abc.com'){
return false;
}
return true;
} protected function failedAuthorization()
{
throw new AuthenticationException('该帐号已被拉黑');
} /**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(){
return [
'account'=>[
'required',
'regex:/^1[34578][0-9]\d{4,8}|(\w)+(\.\w+)*@(\w)+((\.\w+)+)|[0-9a-zA-Z_]+$/',//验证为手机号,邮箱,或帐号
],
'password'=>'required|between:6,18',//验证密码
];
} public function messages(){
return [
'account.required' => '帐号不能为空',
'account.regex' => '帐号不合法',
'password.required' => '密码不能为空',
'password.between' => '密码错误',
];
}

Handler

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\AuthenticationException; class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
]; /**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
]; /**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
} /**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
} protected function unauthenticated($request, AuthenticationException $exception)
{ if($request->expectsJson()){
$response=response()->json([
'status'=>3,
'msg' => $exception->getMessage(),
'errors'=>[],
], 200);
}else{
$response=redirect()->guest(route('login'));
}
return $response;
} protected function invalidJson($request, ValidationException $exception)
{
return response()->json([
'status'=>2,
'msg' => $exception->getMessage(),
'errors' => $exception->errors(),
], $exception->status);
}
}

--------------------- 本文来自 断水流灬 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/duanshuiliu2017/article/details/78343408?utm_source=copy

Laravel 5.5 FormRequest 自定义错误消息 postman调试时X-Requested-With设为XMLHttpRequest的更多相关文章

  1. laravel的Validation检索验证错误消息

    基本用法 处理错误消息 错误消息和视图 可用的验证规则 有条件地添加规则 自定义错误消息 自定义验证规则 基本用法 Laravel提供了一个简单.方便的工具,用于验证数据并通过validation类检 ...

  2. jquery.validate使用 - 自定义错误信息

    自定义错误消息的显示方式 默认情况下,验证提示信息用label元素来显示, 并且会添加css class, 通过css可以很方便设置出错控件以及错误信息的显示方式. /* 输入控件验证出错*/form ...

  3. PHP Lumen Laravel 解决validate方法自定义message无效的问题

    /** * 由于 \Laravel\Lumen\Routing\ProvidesConvenienceMethods::validate 在验证不通过时, * 抛出 \Illuminate\Valid ...

  4. 自定义错误throw

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. Yii自定义错误提示消息

    英文原文: http://www.yiiframework.com/wiki/1/how-to-customize-the-error-message-of-a-validation-rule/ Va ...

  6. Laravel之加密解密/日志/异常处理及自定义错误

    一.加密解密 1.加密Crypt::encrypt($request->secret) 2.解密try { $decrypted = Crypt::decrypt($encryptedValue ...

  7. Laravel自定义错误提示,自定义异常类提示,自定义错误返回信息,自定义错误页面

    方法一 新增CustomException.php文件 App\Exceptions\CustomException.php <?php namespace App\Exceptions; us ...

  8. Spring boot 学习笔记 1 - 自定义错误

    Spring Boot提供了WebExceptionHandler一个以合理的方式处理所有错误的方法.它在处理顺序中的位置就在WebFlux提供的处理程序之前,这被认为是最后一个处理程序. 对于机器客 ...

  9. 【WCF】自定义错误处理(IErrorHandler接口的用法)

    当被调用的服务操作发生异常时,可以直接把异常的原始内容传回给客户端.在WCF中,服务器传回客户端的异常,通常会使用 FaultException,该异常由这么几个东东组成: 1.Action:在服务调 ...

随机推荐

  1. OFIFG fault when using DCO in MSP430

    The OFIFG flag always set in my recent MSP430 smoke device project. In this A sample hardware, there ...

  2. 几个OOD概念

    Composition vs. Aggregation Composition和Aggregation都是”包含”的关系 (part of, made up of) ,不同的是生命周期.对于Compo ...

  3. C#_从DataTable中检索信息

    C#_从DataTable中检索信息 存在于内存中的虚拟表DataTable,绑定在数据显示控件后,如果想在再检索其中某些信息,可以利用DataTable.Select方法进行检索,避免了重复的读取数 ...

  4. 详解Linux查看实时网卡流量的几种方式(转)

    转自https://www.jb51.net/article/112965.htm 假如Keepalived有10个VIP,怎么查看每个VIP的流量呢? 这里就可以使用sar命令查看网卡流量了.前提是 ...

  5. 20165308 2017-2018-2 《Java程序设计》第2周学习总结

    20165308 2017-2018-2 <Java程序设计>第2周学习总结 教材学习内容总结 标识符与关键字 基本数据类型 输入输出数据 循环语句 break continue语句 if ...

  6. java BIO/NIO

    一.BIO Blocking IO(即阻塞IO); 1.      特点: a)   Socket服务端在监听过程中每次accept到一个客户端的Socket连接,就要处理这个请求,而此时其他连接过来 ...

  7. 与左侧的 圆括号“(”(位于“e:\大二上课程课件、作业和答案\数据结构\chapter4\sqstack\sqstack\mysqstack.h(23)”)匹配之前遇到文件结束

    错误原因是“某对圆括号只打了左括号而没有右括号”,debug方法是:直接根据报错提示:“与左侧的 圆括号“(”(位于“e:\大二上课程课件.作业和答案\数据结构\chapter4\sqstack\sq ...

  8. hdfs 例子

    package hadoop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; ...

  9. MySQL分析数据运行状态利器【SHOW PROCESSLIST】

    这个博文,将只是简单的记录一下,我们的数据库操作和使用中,加索引加不上去,分析的过程,其实比较简单,就是看有没有连接进程还在操作表.有的话,将其停掉(不影响业务的场景下). 今天的主角是: SHOW ...

  10. WyBox用usb口驱动4G模块EC20

    按照: http://wiki.openwrt.org/doc/howtobuild/wireless-router-with-a-3g-dongle 然后: 进入linux-3.10.49/driv ...