Sunday, June 2, 2013

jQuery - Create custom rules for validation plugin

Suppose we need a strong password like that in post javascript-form-validation:
  • has lower and upper case
  • has digital
  • has special character
How we can do this with jQuery validation plugin?

Obviously, we need add our custom rules for the plugin and luckily, it is quite simple. - Use addMethod
  jQuery.validator.addMethod("hasLower", function(value, element) {
      return this.optional(element) || (element.value.match(/[a-z]/));
  }, "Must have lower case character.");
  
  jQuery.validator.addMethod("hasUpper", function(value, element) {
      return this.optional(element) || (element.value.match(/[A-Z]/));
  }, "Must have upper case character.");
  
  jQuery.validator.addMethod("hasDigital", function(value, element) {
      return this.optional(element) || (element.value.match(/\d+/));
  }, "Must have digital.");
  
  jQuery.validator.addMethod("hasSpecial", function(value, element) {
      return this.optional(element) || (element.value.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/));
  }, "Must have special character, such as !,@,#,$,%,^,&,*,?,_,~,-,(,).");

Now the password rule is like this
     pass1: {
         required: true,
         minlength: 8,
         maxlength: 30,
         hasLower: true,
         hasUpper: true,
         hasDigital: true,
         hasSpecial: true
     },

It works!








No comments:

Post a Comment