我有一个生成json的控制器,如果错误消息也变为json,如何从验证器中获取错误消息,
$this->validate($request,[
'product_type' => 'required',
'product_name' => 'required|string',
'qty' => 'required',
]);
-- code for saving process here --
return response()->json([
'status' => 'success',
'msg' => 'data succesfuly added'
]);
这是我在网络预览中的回报
errors: {product_type: ["The Product Type name field is required."], product_name: ["The address field is required."],…}
product_name: ["The product_name field is required."]
0: "The address field is required."
qty: ["The qty field is required."]
0: "The qty field is required."
我尝试使用ajax,但是没有用
success: function(response) {
Object.keys(response.errors)
.forEach(function eachKey(key) {
createAlert(response.errors[key], "danger");
});
}
$validator = Validator::make($request->all(), [
'product_type' => 'required',
'product_name' => 'required|string',
'qty' => 'required',
]);
if ($validator->fails()) {
//pass validator errors as errors object for ajax response
return response()->json(['errors'=>$validator->errors()]);
}
您可以使用$validator->messages()
或$validator->errors()
返回array
,其中包含有关validator
的所有信息,包括错误。 json
函数采用array
并将其编码为json
字符串。
因此在客户端,您可以通过以下方式获得错误对象:
$.ajax().done(function(response){
//check if response has errors object
if(response.errors){
// do what you want with errors,
}
});