Skip to content

Instantly share code, notes, and snippets.

@sworup
Last active July 9, 2021 13:04
Show Gist options
  • Save sworup/d007c302733b8018c0ec47210326291f to your computer and use it in GitHub Desktop.
Save sworup/d007c302733b8018c0ec47210326291f to your computer and use it in GitHub Desktop.
Handling of Laravel validation message when pulled through Ajax request
error: function (request) {
// Validation error would return 422 header
if (request.status == 422) {
// Parser the json response expected
var $errors = $.parseJSON(request.responseText);
// Bootstrap alert scafolding for error
var errorsHtml = '<div class="alert alert-danger alert-dismissible"><button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button><h4><i class="icon fa fa-times"></i>Opps! Seems like you didn\'t fill the form properly...</h4><ul>';
// The root nodes are field names, with an array of error messages
$.each( $errors, function( key, value ) {
// We loop through the error to see if there are multiple error associated with the field
$.each( value, function( key2, error ) {
errorsHtml += '<li>' + error + '</li>';
});
});
errorsHtml += '</ul></div>';
$( '#form-errors' ).html( errorsHtml );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment