Home > Java Script > Today’s Learning: Conditional validations using jquery

Today’s Learning: Conditional validations using jquery

Generally we have validations set in validation rules object. This way we can set static rules for a field. What if we have to validate a field depending upon input of other field (conditional validation).

For example: if area-code is entered, make phone field mandatory etc.

Here is a javascript code which adds validation rules according to the condition:

//The validator object

var validatorObject = {

rules: {

‘first_field_id’: {    

required: false,

minlength: 1,

maxlength: 50

 },

‘second_field_id’: {         

required: false,

minlength: 1,

maxlength: 25

}

}

}

$(“#first_field_id”).focusout(function(){

          var newRule = {

                   required: {

                             depends: function(element) {

                              //check if first field is set        

if ($(this).val() != ”) {

                                                return true;

                                      }else{

                                                return false;

                                      }

                             }

                   }

          };

          $(“#second_field_id”).rules(‘add’,newRule);

          $(“#second_field_id”).valid();

}

Now validate the form

$(“#form_id”).validate(validatorObject);

Advertisements
Categories: Java Script
  1. April 8, 2016 at 2:05 pm

    Essa vaca fica dando o rabo por ai e somos nu00f3s que pagamos o pato. Se ela nu00e3o queria ser filmada por quu00ea nu00e3o foi dar em um lugar discr Click https://twitter.com/moooker1

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: