Laravel 5.5 FormRequest 自定义错误消息

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

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

  但我想要的是
  

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

  1. use Illuminate\Validation\ValidationException;
  2. use Illuminate\Auth\Access\AuthorizationException;

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

  1. <?php
  2. namespace App\Http\Requests;
  3. use Illuminate\Foundation\Http\FormRequest;
  4. use Illuminate\Auth\AuthenticationException;
  5. class LoginPost extends FormRequest
  6. {
  7. /**
  8. * Determine if the user is authorized to make this request.
  9. *
  10. * @return bool
  11. */
  12. public function authorize(){
  13. if($this->input('account')=='aaa@abc.com'){
  14. return false;
  15. }
  16. return true;
  17. }
  18. protected function failedAuthorization()
  19. {
  20. throw new AuthenticationException('该帐号已被拉黑');
  21. }
  22. /**
  23. * Get the validation rules that apply to the request.
  24. *
  25. * @return array
  26. */
  27. public function rules(){
  28. return [
  29. 'account'=>[
  30. 'required',
  31. 'regex:/^1[34578][0-9]\d{4,8}|(\w)+(\.\w+)*@(\w)+((\.\w+)+)|[0-9a-zA-Z_]+$/',//验证为手机号,邮箱,或帐号
  32. ],
  33. 'password'=>'required|between:6,18',//验证密码
  34. ];
  35. }
  36. public function messages(){
  37. return [
  38. 'account.required' => '帐号不能为空',
  39. 'account.regex' => '帐号不合法',
  40. 'password.required' => '密码不能为空',
  41. 'password.between' => '密码错误',
  42. ];
  43. }

Handler

  1. <?php
  2. namespace App\Exceptions;
  3. use Exception;
  4. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  5. use Illuminate\Validation\ValidationException;
  6. use Illuminate\Auth\AuthenticationException;
  7. class Handler extends ExceptionHandler
  8. {
  9. /**
  10. * A list of the exception types that are not reported.
  11. *
  12. * @var array
  13. */
  14. protected $dontReport = [
  15. //
  16. ];
  17. /**
  18. * A list of the inputs that are never flashed for validation exceptions.
  19. *
  20. * @var array
  21. */
  22. protected $dontFlash = [
  23. 'password',
  24. 'password_confirmation',
  25. ];
  26. /**
  27. * Report or log an exception.
  28. *
  29. * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
  30. *
  31. * @param \Exception $exception
  32. * @return void
  33. */
  34. public function report(Exception $exception)
  35. {
  36. parent::report($exception);
  37. }
  38. /**
  39. * Render an exception into an HTTP response.
  40. *
  41. * @param \Illuminate\Http\Request $request
  42. * @param \Exception $exception
  43. * @return \Illuminate\Http\Response
  44. */
  45. public function render($request, Exception $exception)
  46. {
  47. return parent::render($request, $exception);
  48. }
  49. protected function unauthenticated($request, AuthenticationException $exception)
  50. {
  51. if($request->expectsJson()){
  52. $response=response()->json([
  53. 'status'=>3,
  54. 'msg' => $exception->getMessage(),
  55. 'errors'=>[],
  56. ], 200);
  57. }else{
  58. $response=redirect()->guest(route('login'));
  59. }
  60. return $response;
  61. }
  62. protected function invalidJson($request, ValidationException $exception)
  63. {
  64. return response()->json([
  65. 'status'=>2,
  66. 'msg' => $exception->getMessage(),
  67. 'errors' => $exception->errors(),
  68. ], $exception->status);
  69. }
  70. }

--------------------- 本文来自 断水流灬 的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. eclipse操作(备忘)

    myecplise破解   https://blog.csdn.net/by_xiaobai007/article/details/81177367 1.查看类路径 2.建立模板 window--pr ...

  2. Java基础二(变量、运算符)

    1.变量2.运算符 ###01变量概述 * A: 什么是变量? * a: 变量是一个内存中的小盒子(小容器),容器是什么?生活中也有很多容器,例如水杯是容器,用来装载水:你家里的大衣柜是容器,用来装载 ...

  3. 使用.pth文件扩展python环境路径

    使用.pth文件扩展python环境路径 有时候我们不希望把一个库放到 site-packages 下面,而是更愿意把它保留在原始的工程目录中,方便管理和维护.那么怎么能让 Python 运行环境找到 ...

  4. Linux(CentOS7.0)下 C访问MySQL (转)

    按语:      最近项目在云服务器上 centos6.8,安装了mysql5.5.39 server和client,但C连接不知所措: 后在官网下载了 devel.share .share-comp ...

  5. dojo DataGrid实现表格数据编辑的解决方案

    在官网上看见的DataGrid编辑非常简单,但我实现的时候总是出现问题.经过N久的摸索,终于搞定了,期间出现了多处困难,下面说些解决办法的流程. 我实现的表格在页面加载时是不显示数据,只有通过表单像服 ...

  6. Zookeeper 配置集群环境详解

    在Linux环境下安装zookeeper 在Linux环境下安装zookeeper 1.       将zookeeper-3.4.13.tar.gz复制到linux操作系统 2.       通过p ...

  7. Linux paste命令详解

    Linux paste命令 Linux paste命令用于合并文件的列.paste指令会把每个文件以列对列的方式,一列列地加以合并 将每个指定文件里的每一行整合到对应一行里写到标准输出,之间用制表符分 ...

  8. Visual Studio 2010 出现关于ActivityLog.xml错误的解决方案

    在用VS编写程序是第一次会跳出“Visual Studio has encountered an exception.This may be caused by an extension. You c ...

  9. JAVAFX开发桌面应用

    javafx中文版文档: http://www.yiibai.com/javafx/ JavaFX之FXController详解 JavaFx系列教程 含打包部署 javafx之两种局部界面的呈现方式 ...

  10. 阅读<All Digital VCXO Replacement for Gigabit Transceiver Applications>笔记(2)---XAPP589

    阅读<All Digital VCXO Replacement for Gigabit Transceiver Applications>笔记(2)---XAPP589 1. 2. 3. ...