6

I am using JQuery Validation. Now I want my rules to be invoked only when certain condition is satisfied, namely, I want $("#AppSelectField").is(':hidden') to return false, only then I invoke the rules.

My rules is as follow:

$(function() {
    $("#RequestLock").validate({
        rules: {
        FloorNum:{
        required: true,
        digits: true
        },


    },
    message: {
     FloorNum: "The floor number must be integer",

},

});
});

How to modify the above section to satisfy my needs? Note I don't want to write my own custom method for required and digits.

1 Answer 1

16

This should do it:

$(function() {
    var checkIfFieldVisible = function() {
        return !$("#AppSelectField").is(':hidden');
    };

    $("#RequestLock").validate({
        rules: {
            FloorNum: {
                required: { depends: checkIfFieldVisible },
                digits: { depends: checkIfFieldVisible }
            }, // <-- EXTRA COMMA
        },
        message: {
            FloorNum: "The floor number must be integer",
        }, // <-- EXTRA COMMA
    });
});

(I marked some extra commas you have on your code, as they will make IE choke)

Sign up to request clarification or add additional context in comments.

2 Comments

Can we validate/not validate entire form based on certain values?. For example I have a nested form with save / submit buttons. I want to validate only on Submit. My problem is when I have the class="required" on each field as the form is very dynamic. Please help.
You don't even need the function, you can just set depends = '#AppSelectField:visible'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.