在Laravel 5.1项目中
我将此Ajax响应视为错误
{"errors":["The Address Name field is required.","The Recipient field is required.","The Address field is required."]}
如果它不是验证中的Ajax响应,我们使用has方法来确定哪个字段有错误。
如您所见,存在3个字段有错误。我正在使用twitter-bootstrap,我想在图像中显示这些错误
我如何获得字段名称?我需要一个像普通请求一样的方法。
答案 0 :(得分:3)
最简单的方法是利用验证器的MessageBag
对象。它返回键上的字段名称。这可以这样做:
// Setup the validator
$rules = array('email' => 'required|email', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
// Validate the input and return correct response
if ($validator->fails())
{
return Response::json(array(
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
), 400); // 400 being the HTTP code for an invalid request.
}
return Response::json(array('success' => true), 200);
这会给你一个像这样的JSON响应:
{
"success": false,
"errors": {
"email": [
"The E-mail field is required."
],
"password": [
"The Password field is required."
]
}
}