douhei8633 2014-10-26 22:04
浏览 87
已采纳

如何在Laravel中处理JSON返回的验证器错误

have my form submitting via AJAX and returning the errors from the validator but not sure how to access them.

So I am returning the errors like so in my controller:

$validator = Validator::make($data, $rules, $messages);

if ($validator->fails()) {
  return Response::json(array(
    'errors' => $validator->messages()->all(),
    200)
  );
}

And (using firebug) I see the JSON is:

errors: Array
  0: "This field is required"

And so on. Im looking for a way to handle all possible errors and display them to the user.

Normally I would return in my controller:

'empty-field' => true

And then in my AJAX call:

success: function(data) {
  if(data.empty-field == true) {
    // inform the user of failure
  }
}

But this will soon become tedious checking for and sending every possible error via JSON. Any way I can simply check for any errors returned and handle them? Much like the way Laravel handles errors when not using AJAX:

@if($errors->has('field'))
  <p class="input-message input-error full-width">{{ $errors->first('field') }}</p>
@endif

Thanks.

  • 写回答

1条回答 默认 最新

  • dougong7850 2014-10-26 22:12
    关注

    With JS data.empty-field is data.empty substract field, you should use data['empty-field']

    And as in Laravel templates, you can count errors : errors.length without check each one.

    success: function(data) {
      if(data.errors.length) {
        alert('There are ' + data.errors.length + ' errors');
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ssh登录页面的问题
  • ¥60 渗透一个指定银行app,拿到客户信息,需要什么级别
  • ¥50 关于在matlab上对曲柄摇杆机构上一点的运动学仿真
  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.
  • ¥15 windows c++内嵌qt出现数据转换问题。
  • ¥15 stm32 串口通讯过程中的问题
  • ¥20 公众号如何实现点击超链接后自动发送文字
  • ¥15 用php隐藏类名和增加类名
  • ¥15 算法设计与分析课程的提问