[英]Returning validation error message as JSON
I want to return a failed validation attempt message in JSON from laravel's validator.我想从 laravel 的验证器返回 JSON 中的验证尝试失败消息。 But upon failed validation I get an 'invalid JSON response' instead.
但在验证失败后,我得到一个“无效的 JSON 响应”。 It is not returning any of the custom messages.
它不返回任何自定义消息。 What am I doing wrong?
我究竟做错了什么?
Controller Controller
public function uploadArtwork(Request $request) {
$validator = Validator::make(request()->all(), [
'artwork-title' => 'required|max:240',
'artwork-description' => 'max:120|nullable',
'artwork-medium' => 'max:120|nullable',
'artwork-software' => 'max:120|nullable',
'artwork-tags' => 'max:120|nullable',
'files' => 'required',
'files.*' => 'required|mimes:jpeg,png,jpg,gif|max:5024',
],
[
'artwork-title.required' => 'Error: Please add title',
'files.required' => 'choose a photo.',
'files.image' => 'file should be an image.',
'files.max' => 'Your photo is too large',
'files.mimes' => 'We only accept :values.',
]
);
if ($validator->fails()) {
return response()->json($validator->errors());
}
js js
error: function (file, response) {
// $("#status-message").text(responseText);
console.log(response);
}
Actually, above way you didn't send an error response.实际上,上述方式您没有发送错误响应。 You are sending a successful response.
您正在发送成功的响应。 If you change something like the below will work.
如果您更改以下内容将起作用。
if($validator->fails()){
return response()->json([
'status' => 'error',
'message' => $validator->getMessageBag()
], 400);
}
For more info refer: Return validation error message as JSON - Laravel 6有关详细信息,请参阅: 返回验证错误消息为 JSON - Laravel 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.