如果在FormRequest Laravel中验证失败,如何添加额外的数据作为响应 [英] How to add extra data in response if Validation fails in FormRequest Laravel
问题描述
如果在FormRequest中验证失败,我需要添加自定义标签作为响应.
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');
}
});
}
}
如果我的任何验证都仅失败,那么我需要在json响应中添加 status = error
,否则我需要添加 status = success
.
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
.
我的响应状态也嵌套在 errors
标签下,我需要将其设置为0级.
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"
]
}
}
目的是我正在发送Ajax请求以提交表单,我需要一个标志来标识是否发生错误.有没有更好的方法可以做到这一点.如果我问一个愚蠢的问题,请原谅我.我是laravel的新手.任何帮助将不胜感激.
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.
推荐答案
从文档中(搜索"AJAX"):
From the docs (search for "AJAX"):
在AJAX请求期间使用validate方法时,Laravel将不会生成重定向响应.相反,Laravel会生成一个包含所有验证错误的JSON响应.此JSON响应将以422 HTTP状态代码发送.
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.
在您的Javascript中,您可以在 a .fail()
处理程序.
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);
}
});
这篇关于如果在FormRequest Laravel中验证失败,如何添加额外的数据作为响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!