December 19, 2006

Simple ZIP/Postal code validation

Simple javascript function to validate 5 digit US ZIP Code and Canadian Postal code format.

US ZIP Codes in the format "NNNNN".
Canadian Postal Codes in the format "LNL NLN".

Returns true if valid, false if not. This example needs the id of the ZIP/Postal Code field to be named "zipcode".

function validZip() {
   var zip = document.getElementById('zipcode').value;
   var zipRegExp = /(^\d{5}$)|(^\D{1}\d{1}\D{1}\s\d{1}\D{1}\d{1}$)/;
   return zipRegExp.test(zip);


Anonymous said...

Works like a charm, thanks a million.

Anonymous said...

works great, thanks!