JQuery validation with multiple inputs

There are many people asking a similar question, but all the answers are in one error message that is built into the API.

.validate({
    groups: {
        birthday: "month day year"
    },

      

Please check this jsfiddle http://jsfiddle.net/atLV4/36/

If you submit without running anything, all items get an error class. When you fill out the form, you can only update one item, deselect it, and the error message will go away even if no other items have been updated. Also, the border disappears as soon as you update the selection that triggers the jumping. I want the check to be done only after all 3 inputs have been selected.

+3


source to share


1 answer


Unfortunately, it looks like jQuery Validate doesn't have a built in function onchange

where you want to put this for your 3 favorites. Instead, you need to turn off validation onfocusout

and onclick

then add an external event change

for the 3 selections that trigger validation after all 3. You need the following for your validation code:

   //save the validate object to use later!
    var $validate = $("#commentForm").validate({
        onfocusout: false,
        onclick: false,
        groups: {
            birthday: "month day year"
        },
        errorPlacement: function (error, element) {
            var name = element.prop("name");
            if (name === "month" || name === "day" || name === "year") {
                error.insertAfter("select[name='year']");
            } else {
                error.insertAfter(element);
            }
        }
    });

      

And you also need a change event handler:



//I'm using generic selectors here, but you may need to specify the 3 of interest
$('select').change(function () {
    if ($('select:filled').length == 3) {
        $('select').each(function () {
            $validate.element(this);
        });
    }
});

      

$ validate.element () is the function that actually verifies that they pass the rules and updates their bounds and error messages accordingly. The test is $('select:filled')

just short to confirm that all 3 choices matter.

Working example here: http://jsfiddle.net/atLV4/41/

+1


source







All Articles