Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Rule Validation in JQuery

Tags:

jquery

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.

like image 914
Graviton Avatar asked Jul 07 '09 07:07

Graviton


People also ask

How to use if condition in jquery validation?

In this article, the solution of How To Use If Condition In Jquery Validation will be demonstrated using examples from the programming language. $("#client-form"). validate({ focusInvalid: false, ignore: [], rules: { salaryband: { required: function(element) { return $('#job-earnings-salary').is(':checked') } } } });


1 Answers

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)

like image 106
Paolo Bergantino Avatar answered Oct 05 '22 08:10

Paolo Bergantino