Ian Hoar – Passion for Technology – Geeking Out - Technology, Web, Toys, Games, Design, Entertainment, Gadgets, & Geeking Out

jQuery validator plugin – custom method for postal code validation

With my previous post on jQuery, I thought I would share a simple add-on method for the jQuery Validation plugin. If you are from Canada or writing a Canadian validation form with a postal code field you can use this. Just add the code below in your rules script.

// Addon method for validating postal codes. Valid
// formats are (X1X 1X1) or (X1X1X1) or (X1X-1X1).
$.validator.addMethod("postalCode", function(value) {
     return value.match(/^[a-zA-Z][0-9][a-zA-Z](-| )?[0-9][a-zA-Z][0-9]$/);
}, 'Please enter a valid postal code');

Then you can use the rules required:true and postalCode:true in your rule set.

6 Comments to “jQuery validator plugin – custom method for postal code validation”

Responses:

Your comments are important, join the conversation