victorjonsson / jQuery-Form-Validator

[DISCONTINUED] jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code.
972 stars 476 forks source link

How to validate only a subset of a large form? #638

Open iamjoshleung opened 7 years ago

iamjoshleung commented 7 years ago

I have a very large form and would like to separate it into multiple steps. Before a user proceeds to the next setup, form elements in the last setup must be validated first.

Therefore, how to use this plugin to validate only a subset of a form?

dhewer commented 6 years ago

I just figured this out for a project, and in case it's useful to you or others, here's how I ended up doing it. This method only works if only one panel is visible at a time.

HTML setup: Each area of the form is wrapped in a div with a .panel class. Each required input in each panel needs either a data-validation attribute or a .required class. You'll need a button or something to trigger the panel validation. (Ex, button with the .btn-next class.)

jQuery Code: On form load, hide the panels (either with CSS or $('.panel').hide()) and show just the first one $('.panel').first().show(). Whenever the Next button is clicked, it checks each input inside the current visible panel (via .panel:visible) to see if it is valid. If all within the panel are valid, it hides the current panel and shows the next panel.

Simplified example code to determine if the current panel is valid:

$('.btn-next').click(function(){
    var panelValid = true;
    // The find function should list all of the form elements that you want to validate
    $('.panel:visible').find('.required, [data-validation="required"], [data-validation="custom required"], [data-validation="recaptcha"]').each(function(){
        // Call Form-Validator function on the element found
        $(this).validate(function(isValid, el) {
            if (!isValid) panelValid = false;
        });
    }); // end checking each input
    if (panelValid) {
        // Entire panel is valid; do what you gotta do ...
        // Ex, hide current panel, show the next one
    } else {
        // At least one required element is not valid
    }
}); // end next button click