1

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
  • You have to set the HTTP status to one of the Error Codes. Like 400. Then use the ajax error callback. Commented Oct 26, 2014 at 22:11

1 Answer 1

1

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');
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.