以JSON格式返回验证错误消息-Laravel 6 [英] Return validation error message as JSON - Laravel 6
问题描述
我想以JSON返回失败的验证尝试消息.我以前使用过类似的东西,我认为它正在Laravel 5上工作.
I want to return a failed validation attempt message in JSON. I used something like this before, which was working on Laravel 5, I believe...
if ($validator->fails()) {
return response()->json($validator->messages(), 200);
}
但是,对于我们的新项目,我们使用的是Laravel 6,上面的代码只是返回一个空白页.
However, for our new project we are using Laravel 6 and the above just returns a blank page.
在Laravel 6中,以下内容成功返回了错误消息,尽管不是JSON ...
In Laravel 6 the following returns the error message successfully, albeit not in JSON...
if ($validator->fails()) {
$msg = $validator->messages();
dd($msg);
}
在Laravel 6中, response()
的工作方式必须有所改变.
There must be a change in the way response()
works in Laravel 6.
有什么想法可以使Laravel 6中的JSON中返回验证消息吗?谢谢.
Any ideas how I get the Validation messages to get returned in JSON in Laravel 6? Thanks.
推荐答案
在这里,
if($validatedData->fails()){
return response()->json([
'status' => 'error',
'message' => $validatedData->getMessageBag()
],400);
}
您可以在JSON中捕获这些错误,这是示例代码
You can grab these errors in JSON, This is sample code
$.ajax({
url: "{{ route('your_route_name') }}",
method: 'post',
cache: false,
contentType: false,
processData: false,
data: formData,
success: function(response){
//....YOUR SUCCESS CODE HERE
},
error: function(response){
// HERE YOU CAN GET ALL THE ERRORS IN JSON
var data = JSON.parse(response.responseText);
if(data.message){
if(data.message.f_name){
$('input[name=f_name]')
.parents('.form-group')
.find('.help-block')
.html(data.message.f_name)
.css('display','block');
}else{
$('input[name=f_name]')
.parents('.form-group')
.find('.help-block')
.html('')
.css('display','none');
}
}else{
$('.help-block').html('').css('display','none');
}
}
});
这篇关于以JSON格式返回验证错误消息-Laravel 6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!