简体   繁体   English

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

[英]How to handle JSON returned validator errors in Laravel

have my form submitting via AJAX and returning the errors from the validator but not sure how to access them. 让我的表单通过AJAX提交并从验证程序返回错误,但不确定如何访问它们。

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: 并且(使用firebug)我看到的JSON是:

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: 然后在我的AJAX呼叫中:

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. 但这很快就会变得乏味,无法通过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: 与不使用AJAX时Laravel处理错误的方式非常相似:

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

Thanks. 谢谢。

With JS data.empty-field is data.empty substract field , you should use data['empty-field'] 对于JS data.empty-fielddata.empty substract field ,应使用data['empty-field']

And as in Laravel templates, you can count errors : errors.length without check each one. 就像Laravel模板一样,您可以计算错误:errors.length而无需检查每个错误。

success: function(data) {
  if(data.errors.length) {
    alert('There are ' + data.errors.length + ' errors');
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM