validate form segments independently

后端 未结 1 1771
孤城傲影
孤城傲影 2021-01-27 09:10

I have a very big form which I am splitting across four segments in a wizard like way. The wizard plugin (smart wizard) has the form segment currently in focus avtive while the

相关标签:
1条回答
  • 2021-01-27 09:37

    Quote OP:

    "In the onLeaveStep option of the wizard plugin, I called the validate plugin. Wether or not the user clicks next or previous validation will be triggered"

    The problem is that .validate() is not a method for "testing" the form's validity. Rather, .validate() is the method for initializing the plugin on the form. You would do it once on page load and any subsequent calls to .validate() are ignored.

    To test the form programatically with the jQuery Validate plugin, you use the .valid() method which triggers a test and returns a boolean.

    The jQuery Validate plugin, by default, will also ignore any "hidden" input elements. So perhaps you can leverage this feature to your advantage when using your wizard plugin.

    within your DOM ready handler...

    $('#myform').validate({
       // rules & options
    });
    

    within your wizard...

    onLeaveStep: function(){
        $('#myform').valid();
    }
    

    Otherwise, when I create multi-step forms, I use a unique set of form tags for each section. Then I use .valid() to test the section before moving to the next. (Don't forget to first initialize the plugin, call .validate(), on each form when the page is fully loaded.) Then on the last section, I use .serialize() on all sections and concatenate each into a data query string to be submitted.

    Something like this...

    $(document).ready(function() {
    
        $('#form1').validate({
            // rules
        });
    
        $('#form2').validate({
            // rules
        });
    
        $('#form3').validate({
            // rules,
            submitHandler: function (form) {
               // serialize and join data for all forms
               // ajax submit
               return false;
            }
        });
    
        $('#gotoStep2').on('click', function() {
            if ($('#form1').valid()) {
                // code to reveal step 2
            }
        });
    
        $('#gotoStep3').on('click', function() {
            if ($('#form2').valid()) {
                // code to reveal step 3
            }
        });
    
        // there is no third click handler since the plugin takes care of this with the
        // built-in submitHandler callback function on the last form.
    
    });
    
    0 讨论(0)
提交回复
热议问题