【问题标题】:Getting Error Field Names in Laravel Ajax Request Validation在 Laravel Ajax 请求验证中获取错误字段名称
【发布时间】:2016-01-25 04:47:05
【问题描述】:

在 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 方法。

【问题讨论】:

  • 为什么不先使用 clent 端验证,然后再使用 PHP 端验证
  • 在发送 ajax 之前同意上述验证。发送请求的唯一方式是验证完成时

标签: php jquery ajax twitter-bootstrap laravel


【解决方案1】:

最简单的方法是利用验证器的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."
        ]
    }
}

【讨论】:

  • 这正是我所需要的
  • 正是我需要的。但是如何在验证期间使我的input field 变为红色?
猜你喜欢
  • 2021-03-11
  • 1970-01-01
  • 2023-03-29
  • 2021-04-11
  • 2020-08-20
  • 2017-07-16
  • 2013-07-23
  • 2018-01-24
  • 2021-01-11
相关资源
最近更新 更多