我想从 laravel 的验证器以 JSON 格式返回失败的验证尝试消息。但是在验证失败后,我会得到一个“无效的 JSON 响应”。它不返回任何自定义消息。我做错了什么?
控制器
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
error: function (file, response) {
// $("#status-message").text(responseText);
console.log(response);
}
答案 0 :(得分:1)
实际上,上述方式您没有发送错误响应。您正在发送成功的响应。如果您更改以下内容将起作用。
if($validator->fails()){
return response()->json([
'status' => 'error',
'message' => $validator->getMessageBag()
], 400);
}