jQuery Zip/Postal Code Validation Method

September 1st, 2009

For those of you who may be familiar with Jörn Zaefferer’s jQuery Validation plugin, I’ve written a method for validating zip/postal code fields, which was not included in the plugin.

To start validating zip/postal code fields, include this code somewhere after you’ve included the plugin:


jQuery.validator.addMethod("postalcode", function(postalcode, element) {
	return this.optional(element) || postalcode.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnpstvxy]{1}\d{1}[A-Za-z]{1} ?\d{1}[A-Za-z]{1}\d{1})$/);
}, "Please specify a valid postal/zip code");

Now you can add postalcode to your validation rules like so:


$("#myform").validate({
	rules: {
		postalcode: {
			postalcode: true
		}
	}
});

Note: this will accept both Canadian postal codes (with or without a space) and U.S. zip codes. Enjoy!

Tweet This

1 Comment to “jQuery Zip/Postal Code Validation Method”

Leave a Reply