I'm using this ajax request to send request using jQuery:
$.ajax({type: 'POST',
url: '/send-review',
data: {
"_token": "{{ csrf_token() }}",
"_id": {{$item->id}},
},
success: function (data) {
console.log(data);
},
error: function (err) {if (err.status == 422) {
// when status code is 422, it's a validation issue
}
}
});
I can show get Laravel validation error in the bottom of each input, but how can I show all of the Laravel validation errors format in one box of HTML using jQuery?
There are lots of way you can show messages . You can print error object . like as
var htmlErr= []
var err.errors.map((data,index)=>{
$(".comment").text(data.comment);
});
in html
<p class="comment"></p>
then you can try with like this. For more error message more class ..
Its just dummy code for accurate code i need to know details about your data/object.
I always use this :
$.ajax({type: 'POST',
...
success: function (data) {
console.log(data);
},
error: function (err) {
if (err.status == 422) {
toastError(err.responseJSON.message);
let details = res.responseJSON.errors ;
Object.keys(details).forEach(field => {
formatErrorUsingClassesAndPopover(field,details[field]);
});
}
}
});
And for Formatting the answer implement the formatErrorUsingClassesAndPopover( element , array_of_problems )
make it as abstract as possible .
for example (Using Bootstrap and jQuery):
function formatErrorUsingClassesAndPopover(element , array_of_problems ){
let someHTML = '';
array_of_problems.forEach(function(e){someHTML+='<li>'+e+'</li>'});
$('#'+element+'_error_section').html('<ul>'+someHTML+'</ul>');
$('#'+element).addClass('is-invalid');
}
...
//don't forget to use this in the ajax success function :
$('input').removeClass('is-invalid');//or you can let the client side validation do it
id
to be field
_error_section .id
to be field
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With