题意:Laravel 5 验证 - 以 JSON/AJAX 形式返回
问题背景:
I am trying to post the values into validation and return the response as json rather than return view
as given in the documentation.
我正在尝试将值提交到验证中,并以 JSON 的形式返回响应,而不是像文档中所示的那样返回视图。
$validator = Validator::make($request->all(), [
'about' => 'min:1'
]);
if ($validator->fails()) {
return response()->json(['errors' => ?, 'status' => 400], 200);
}
The post is made by ajax so I need to receive the response in the ajax as well.
请求是通过 AJAX 发送的,所以我需要在 AJAX 中接收响应。
I figured out that in order to prevent refresh of the page in the returning response, I have to give it a status code of 200 outside the array. But I couldn't figure out what to give the 'errors'
part. What should I write in there?
我发现为了防止在返回响应时刷新页面,我必须在数组外部给出一个 200 状态码。但我无法弄清楚应该在 'errors' 部分写什么。我应该写什么?
问题解决:
You can use $validator->messages()
that returns an array which contains all the information about the validator, including errors. The json
function takes the array and encodes it as a json string.
你可以使用 $validator->messages(),它返回一个包含所有验证信息的数组,包括错误。json 函数将该数组编码为 JSON 字符串。
if ($validator->fails()) {
return response()->json($validator->messages(), Response::HTTP_BAD_REQUEST);
}
Note: In case of validation errors, It's better not to return response code 200. You can use other status codes like 400 or Response::HTTP_BAD_REQUEST
注意:在验证错误的情况下,最好不要返回响应代码 200。你可以使用其他状态码,例如 400 或 Response::HTTP_BAD_REQUEST。