validate form segments independently

泄露秘密 提交于 2019-12-02 08:11:52

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.

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!