19-Feb-2013

Adding filters to jQuery Validation

jQuery is great for doing validation on the fly, but the standard filters do not cover everything like Australian phone numbers for example.from (https://gist.github.com/gilmoreorless/852211)

  /*** Allow digits and whitespace ***/
   
   // Method 1:
   jQuery.validator.addMethod("digitsWhitespace",function(value,element){
   returnthis.optional(element)||/^[\d\s]+$/.test(value);
   },jQuery.validator.messages.digits);
   
   // Method 2:
   jQuery.validator.addMethod("digitsWhitespace",function(value,element){
   returnjQuery.validator.methods.digits(value.replace(/\s/g,''),element);
   },jQuery.validator.messages.digits);
   
   /*** Australian phone number formats ***/
   
   // Australian phone number
   jQuery.validator.addMethod("phoneAU",function(value,element){
   returnthis.optional(element)||/^(\+?61|0)\d{9}$/.test(value.replace(/\s+/g,""));
   },"Please specify a valid phone number");
   
   // Australian mobile phone number
   jQuery.validator.addMethod("mobileAU",function(value,element){
   returnthis.optional(element)||/^(\+?61|0)4\d{8}$/.test(value.replace(/\s+/g,""));
   },"Please specify a valid mobile phone number");

Leave a Reply

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram