jQuery-Form-Validator icon indicating copy to clipboard operation
jQuery-Form-Validator copied to clipboard

validate function called more than once when "on('validation')" is called

Open amjo opened this issue 5 years ago • 0 comments

i have a pretty huge form with many types of fields (date, numbers, text, checkboxes, radios, etc..).

One of the important behaviors i need form my form is to be able to save form fields individually on blur... of course, i need to validate each field on blur, and if it's a valid field, we call a "saveField()" function.

Naturally, i initialize the form validation with:

$.validate({
        form: '#form-1',
        modules: 'location, logic, html5, security',
        onModulesLoaded: function() {
            $('input.hasCountry').suggestCountry();
        },
    });

later on add an event listener to the "validation" event for each form field (i haven't added a "Blur" event listener, since form validator already takes care of that for me... so below is the on("validation") method:

$('input:not([type=radio]),textarea')
        .on('validation', function(evt, valid) {
            var error_div = $(this).parents(".parent-input").find('.custom-error');

            if (!valid) {
                var error_message = evt.target.dataset.validationErrorMsg;
                if (!error_message) {
                    error_message = "Please provide a valid input";
                }
                error_div.html(error_message);
            } else {
                error_div.html("");

								// saveField();
                console.log("I CALL THE SAVE FUNCTION!");
            }
        })
        .on('beforeValidation', function(value, lang, config) {
            var error_div = $(this).parents(".parent-input").find('.custom-error');
            error_div.html("");
        });

Here's what's weird! When i type something, and focus out: - the console.log("I CALL SAVE...."); is triggered... once! (this is expected) but try to focus on it again, i get the console.log() fired twice => meaning the on("validation") is being triggered twice.

JSFiddle Link: https://jsfiddle.net/tg3h16ec/4/ Open up your browser's console and follow the above mentioned steps by typing something and focusing out. then just type something and focus out again. you'll notice the the console.log() count is initially 1, then it starts incrementing by 2 each time.

amjo avatar Jun 28 '19 11:06 amjo