Archive

Archive for January, 2013

Today’s Learning: Conditional validations using jquery

January 15, 2013 1 comment

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);

Categories: Java Script