Last active
July 9, 2021 13:04
-
-
Save sworup/d007c302733b8018c0ec47210326291f to your computer and use it in GitHub Desktop.
Handling of Laravel validation message when pulled through Ajax request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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