Edgar
Edgar

Reputation: 1131

jquery validator plugin - changing validation rules dynamically

Heres the code that im working with:

$('#button').click( function (e) {
  var rules = rules_data; //object that holds all rules for form validation

  if (a == b) { //some random criteria 
    delete object.rule5; //deletes specific rule (in this case 'rule5') out of object if criteria is met, otherwise the rules object is unchanged  
  }

  var validate_form = $('#form').validate(rules);

  if (validate_form === false) {
    e.preventDefault();
  }
});

My problem with this code - even tho the rules object changes like it supposed to on each button click (if criteria is met), the validation only takes rules of the 1st click and gets stuck with those rules even if rules were changed. I mean, if rules are changed on button click, i want the validation to discard the old rules and apply the new ones, but that is not happening for some reason.

Any suggestions? Maybe im doing something wrong here?

Upvotes: 1

Views: 3595

Answers (2)

Sparky
Sparky

Reputation: 98748

.validate() is the method of initializing the plugin on the form. It can only be called once on the page and if you try to call it again, no matter what options you pass, it will do nothing.

So you'll want to remove .validate() from your click handler and put it inside the DOM ready handler.

AFAIK, the only way to change your rules dynamically is to replace them using the built-in rules('add') method.

If you have a rule for your input called field1, initially defined like this...

rules: {
    field1: {
        required: true,
        number: true
    }
}

You could only change this field's rules by replacing them. Use the rules('add') method like this...

$('input[name="field1"]').rules('add', {
    required: true,
    number: false,
    minlength: 10
});

If you want to target many fields at once with the same settings, then you'll have to incorporate the jQuery .each() method. Something like this...

$('input').each(function() {
    $(this).rules('add', {
        required: true,
        minlength: 10
    });
});

Upvotes: 3

Ben Barden
Ben Barden

Reputation: 2111

Depending on what your rules sets are, you could turn it around and handle it the other way. Have one or more jquery variables that you use to indicate what the rules are supposed to be, and then have the validation rules themselves check those variables. (you can use javascript vars, too, but have to pay attention to scoping). The validation plugin allows both for conditional application of rules, and for custom rules where the accept/deny is based partially on external variables.

Upvotes: 0

Related Questions