duanqin4238 2017-09-25 16:41
浏览 94
已采纳

如果在FormRequest Laravel中验证失败,如何在响应中添加额外数据

I need to add custom tag in response if the validation fails in FormRequest.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreMessage extends FormRequest
{
    /**
     * 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 [
            'name' => 'required|max:100',
            'email' => 'required|email',
            'message' => 'required|max:1000'
        ];
    }

    public function withValidator(\Illuminate\Validation\Validator $validator)
    {
        $validator->after(function ($validator) {

               if($validator->fails()) {
                   $validator->errors()->add('status', 'error');
               }

        });
    }

}

If my any of the validation fails only then I need to add status = error in json response else I need to add status = success.

Also my response status is nested under errors tag I need it to be at level 0.

    {
  "message": "The given data was invalid.",
  "errors": {
    "name": [
      "The name may not be greater than 100 characters."
    ],
    "status": [
      "error"
    ]
  }
}

Purpose of this is I am sending Ajax request to submit a form i need a flag to identify whether error occurred or not. Is there any better way to do this. Pardon me if I am asking silly question. I am newbie to laravel. Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • doumen9709 2017-09-25 16:55
    关注

    From the docs (search for "AJAX"):

    When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

    In your Javascript, you can catch this happening in a .fail() handler.

    UPDATE Simple example, doesn't handle formatting multiple validation errors but gives you the idea:

    $.ajax( ... )
    .fail(function(xhr, status, error) {
        if (error === 'Unprocessable Entity') {
            // validation failure
            var msg = '';    
            for (error in xhr.responseJSON) {
                msg += xhr.responseJSON[error];
            };
            alert(msg);
        }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集