在 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,我想像图片一样显示这些错误
如何获取字段名称?我需要一个像普通请求一样的 has 方法。
最佳答案
最简单的方法是利用验证器的 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."
]
}
}
关于php - 在 Laravel Ajax 请求验证中获取错误字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33339768/