jQuery Validation: Changing Rules Dynamically

Ahh validation plugin, always so tricky 🙁

First, I added id attributes to all the input boxes. Then, I made a change function for you:

$("input[name="userAction"]").change(function() {
    $('#signupFields').toggle();
    $('#loginFields').toggle();    
    if ($("input[name="userAction"]:checked").val() === "login") {
        removeRules(signupRules);
        addRules(loginRules);
    } else {        
        removeRules(loginRules);
        addRules(signupRules);

    }
});

The add and remove functions look like this:

function addRules(rulesObj){
    for (var item in rulesObj){
       $('#'+item).rules('add',rulesObj[item]);  
    } 
}

function removeRules(rulesObj){
    for (var item in rulesObj){
       $('#'+item).rules('remove');  
    } 
}

That’s pretty much it. See here for a working example: http://jsfiddle.net/ryleyb/wHpus/66/

EDIT: To me, the non-intuitive part is that I don’t see an easy way to add/remove rules to the whole form after you call validate, instead you have to manipulate the individual form elements.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)