I found a way to validate the forms simply by checking if the required fields are empty or not. Plus email fields need to be valid email address in order to proceed.
var exportform_has_error = true; // if exportform_has_error==true, it means there is at least 1 error
$( '.exportform__button' ).on( 'click', function(event) {
var $form = $( event.target ).closest( 'form' );
var has_errors = [];
$form.find( '.wpcf7-validates-as-required' ).each( function( index ) {
if( $(this).hasClass( 'wpcf7-checkbox' ) ) {
// for acceptance + required checkboxes
has_errors[index] = $(this).find( 'input[type=checkbox]' ).prop( 'checked' ) ? 'no' : 'yes';
has_errors[index] == 'no' ? $(this).closest( '.wpcf7-checkbox' ).removeClass( 'wpcf7-not-valid' ).next( '.wpcf7-not-valid-tip' ).hide() : $(this).closest( '.wpcf7-checkbox' ).addClass( 'wpcf7-not-valid' ).next( '.wpcf7-not-valid-tip' ).show();
} else if( $(this).hasClass( 'wpcf7-select' ) ) {
// for required select dropdown multi-option
has_errors[index] = $(this).find( 'select' ).val() != '' ? 'no' : 'yes';
has_errors[index] == 'no' ? $(this).removeClass( 'wpcf7-not-valid' ).next( '.wpcf7-not-valid-tip' ).hide() : $(this).addClass( 'wpcf7-not-valid' ).next( '.wpcf7-not-valid-tip' ).show();
} else if ( $(this).hasClass( 'wpcf7-validates-as-email' ) ) {
// for required email field
has_errors[index] = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i.test(this.value) ? 'no' : 'yes';
has_errors[index] == 'no' ? $(this).removeClass( 'wpcf7-not-valid' ).next( '.wpcf7-not-valid-tip' ).hide() : $(this).addClass( 'wpcf7-not-valid' ).next( '.wpcf7-not-valid-tip' ).show();
} else {
// for other required text fields
has_errors[index] = $(this).val() != '' ? 'no' : 'yes';
has_errors[index] == 'no' ? $(this).removeClass( 'wpcf7-not-valid' ).next( '.wpcf7-not-valid-tip' ).hide() : $(this).addClass( 'wpcf7-not-valid' ).next( '.wpcf7-not-valid-tip' ).show();
}
// if ( has_errors[index] == 'yes' ) {
// console.log( 'error at ' + index );
// }
});
if( jQuery.inArray( 'yes', has_errors ) !== -1 ) {
exportform_has_error = true;
// if there is error in the form,
// add your custom error handling scripts in this section
console.log( 'Form has invalid fields!' );
return;
} else {
exportform_has_error = false;
// if there is NO error in the form,
// add your custom success handling scripts in this section
console.log( 'Form is valid!' );
}
});
})();
Where do you put this code?
@espidesigns
Just perfect! Big thanks!
@codyadamswhiterabbit
You need to place it in your custom js file.