微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php-在Laravel Ajax请求验证中获取错误字段名称

在Laravel 5.1项目中

我收到此Ajax响应错误

{"errors":["The Address Name field is required.","The Recipient field is required.","The Address field is required."]}

如果不是Validation中的Ajax响应,我们将使用has方法来确定哪个字段有错误.

如您所见,存在3个字段有错误.我正在使用twitter-bootstrap,我想显示这些错误,如图所示

enter image description here

如何获得字段名称?我需要像普通请求中那样的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."
        ]
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐