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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀