I am using parsley to validate my form, with ajax and laravel on the server side. Client-side validations work correctly by combining bootstrap styles. This the code:
$('#form_create').parsley({
errorClass: 'is-invalid',
successClass: 'is-valid',
errorsWrapper: '<span class="invalid-feedback"></span>',
errorTemplate: '<div></div>'
}).on('form:validate', function (formInstance) {
console.log('Event: form:validate');
}).on('form:error', function(formInstance){
let errors = formInstance.fields.length;
let message = errors === 1
? 'check the field marked in red'
: 'check the ' + errors + ' fields marked in red';
showErrorsForm(message);
}).on('form:submit', function() {
return false;
}).on('form:success', function(){
$("#btn_submit").prop('disabled', 'disabled');
$.ajax({
method: "POST",
url: $("#form_create").attr('action'),
data: $("#form_create").serialize()
}).done( function(data, textStatus, jqXHR) {
console.log('Done');
}).fail( function (jqXHR, textStatus, errorThrown) {
$("#btn_submit").removeAttr('disabled');
$.each(jqXHR.responseJSON.errors, function(key,value){
$("#"+key).parsley().addError('errorServer', {message: value, updateClass: true});
});
});
});
With this code I assign the errors returned by laravel:
$.each(jqXHR.responseJSON.errors, function(key,value){
$("#"+key).parsley().addError('errorServer', {message: value, updateClass: true});
});
What I am trying to do is that when the client side is revalidated, the server errors returned by laravel are eliminated and only those of parsley validation are displayed. This works individually:
$('#name').parsley().on('field:validate', function() {
$(this.$element).parsley().removeError('errorServer', {updateClass: true});
});
But it is not efficient when the form contains too many fields. Any ideas to implement this? Thanks