user2525513
user2525513

Reputation: 5

validate only when a condition is met in jquery

I have a jquery validation script as follows

$("#form").validate({
rules:{
    type:{
        required:true
         }
      }
});

i want the type field to be required only when update mode is true. How can i enhance this script to do that?

Upvotes: 0

Views: 196

Answers (1)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you could try:

$("#form").validate({
  rules:{
    type:{
        required:function(elem) {
           return +update_mode  > 0; //convert true/false to number and check
        }        
  }
});

In the code, variable update_mode can have either true or false value, and the code checks if update_mode is true, in which case it makes the field required for validation else not-required.

Upvotes: 1

Related Questions