Validate subset of a form using jQuery Validate plugin

耗尽温柔 提交于 2019-12-17 15:46:24

问题


My HTML form has a number of divs that are the steps of a wizard. Upon clicking a "next" button I want to validate just the active div. I'm using the jQuery.Validate.js plugin.

Each div has an ID, so I want a way to say something like:

wizardForm.validate().element('#first-step :input')

but this only validates the first input, not all of them. How can I validate all inputs within a div?


回答1:


Taking what jAndy suggested, I created this helper function:

jQuery.validator.prototype.subset = function(container) {
    var ok = true;
    var self = this;
    $(container).find(':input').each(function() {
        if (!self.element($(this))) ok = false;
    });
    return ok;
}

usage:

if (wizardForm.validate().subset('#first-step')) {
    // go to next step
}



回答2:


I tried this solution and it didn't work for me. So here is how i achieved same behaviour, using jquery.validation plugin.

The validator:

var form = $('#form');

    // init validator obj and set the rules
    form.validate({
        errorElement: 'span', //default input error message container
        errorClass: 'help-inline', // default input error message class
        focusInvalid: false, // do not focus the last invalid input
        ignore: "",
        rules: {
            // the rules, as usual
        },

        highlight: function (element) { // hightlight error inputs
            $(element).closest('.control-group').addClass('error'); // set error class to the control group
        },

        unhighlight: function (element) { // revert the change dony by hightlight
            $(element)
                .closest('.control-group').removeClass('error'); // set error class to the control group
        }
    });

Using bootstrap form wizard.

This is how i validate each step:

$('#step :input').valid()

Works like a charm.




回答3:


If you look at the options for the validate() function one of the options is ignore, which by default will prevent the validator from attempting to validate any fields that match the CSS pseudo-class :hidden. I used this in combination with the FuelUX Wizard and was able to prevent the wizard from progressing to the next step with the following:

$( '#wizard' ).wizard().on( 'change', function( event, info ) {
    if ( ! $( '#wizard_form' ).valid() ) event.preventDefault();
});


来源:https://stackoverflow.com/questions/2636512/validate-subset-of-a-form-using-jquery-validate-plugin

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