Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate with multiple inputs

Theres a lot of people asking a similar question, but all the answers are for a single error message, which 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 elements get the error class. As you fill out the form, you can update only one element, deselect it and the error message will disappear even though the other elements haven't been updated. Also, the border is disappearing as soon as you update the select, which causes jumping. I want the validation to only run once all 3 inputs have been selected.

like image 413
Taylor Chance Avatar asked May 11 '26 00:05

Taylor Chance


1 Answers

Unfortunately, it seems that jQuery Validate doesn't have a built-in onchange function, which is where you'd want to put this for your 3 selects. Instead, you'll want to disable onfocusout and onclick checking, then add an external change event for the 3 selects, which triggers the validation once all 3 are filled. For your validate code, you need this:

   //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 then you will 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 which actually checks that they are passing the rules, and updates their borders and error messages appropriately. Checking for $('select:filled') is just short-hand for confirming that all 3 selects have a value.

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

like image 151
Ryley Avatar answered May 12 '26 15:05

Ryley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!