[javascript] ZIP Code (US Postal Code) validation

I thought people would be working on little code projects together, but I don't see them, so here's an easy one:

Code that validates a valid US Zip Code. I know there are ZIP code databases out there, but there are still uses, like web pages, quick validation, and also the fact that zip codes keep getting issued, so you might want to use weak validation.

I wrote a little bit about zip codes in a side project on my wiki/blog:

https://benc.fogbugz.com/default.asp?W24

There is also a new, weird type of zip code.

https://benc.fogbugz.com/default.asp?W42

I can do the javascript code, but it would be interesting to see how many languages we can get here.

This question is related to javascript validation

The answer is


Are you referring to address validation? Like the previous answer by Mike, you need to cater for the othe 95%.

What you can do is when the user select's their country, then enable validation. Address validation and zipcode validation are 2 different things. Validating the ZIP is just making sure its integer. Address validation is validating the actual address for accuracy, preferably for mailing.


Here's one from jQuery Validate plugin's additional-methods.js file...

jQuery.validator.addMethod("zipUS", function(value, element) {
    return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(value);
}, "Please specify a valid US zip code.");

EDIT: Since the above code is part of the jQuery Validate plugin, it depends on the .addMethod() method.

Remove dependency on plugins and make it more generic....

function checkZip(value) {
    return (/(^\d{5}$)|(^\d{5}-\d{4}$)/).test(value);
};

Example Usage: http://jsfiddle.net/5PNcJ/


As I work in the mailing industry for 17 years I've seen all kinds of data entry in this area I find it interesting how many people do not know their address as it is defined by the USPS. I still see addresses like this:

XYZ College
IT Department
City, St ZIP

The worst part is the mail 99% of the time is delivered, the other 1%, well that is returned for an incomplete address as it should.

In an earlier post someone mentioned USPS CASS, that software is not free.

To regex a zip code tester is nice, I'm using expressions to determine if US, CA, UK, or AU zip code. I've seen expressions for Japan and others which only add challenges in choosing the correct country that a zip belongs to.

By far the best answer is to use Drop Down Lists for State, and Country. Then use tables to further validate if needed. Just to give you an idea there are 84052 acceptable US City St Zip combinations on just the first 5 digits. There are 249 valid countries as per the ISO and there are 65 US State/Territories.

There are Military, PO Box only, and Unique zip code classes as well. KISS applies here.


function isValidUSZip(sZip) {
   return /^\d{5}(-\d{4})?$/.test(sZip);
}

One way to check valid Canada postal code is-

function isValidCAPostal(pcVal) {
   return ^[A-Za-z][0-9][A-Za-z]\s{0,1}[0-9][A-Za-z][0-9]$/.test(pcVal);
}

Hope this will help someone.


Drupal 7 also has an easy solution here, this will allow you to validate against multiple countries.

https://drupal.org/project/postal_code_validation

You will need this module as well
https://drupal.org/project/postal_code

Test it in http://simplytest.me/


This is a good JavaScript solution to the validation issue you have:

/\b\d{5}-\d{4}\b/

To allow a user to enter a Canadian Postal code with lower case letters as well, the regex would need to look like this:

/^([a-zA-Z][0-9][a-zA-Z])\s*([0-9][a-zA-Z][0-9])$/


To further my answer, UPS and FedEx can not deliver to a PO BOX not without using the USPS as final handler. Most shipping software out there will not allow a PO Box zip for their standard services. Examples of PO Box zips are 00604 - RAMEY, PR and 06141 - HARTFORD, CT.

The the whole need to validate zip codes can really be a question of how far do you go, what is the budget, what is the time line.

Like anything with expressions test, test, test, and test again. I had an expression for State validation and found that YORK passed when it should fail. The one time in thousands someone entered New York, New York 10279, ugh.

Also keep in mind, USPS does not like punctuation such as N. Market St. and also has very specific acceptable abbreviations for things like Lane, Place, North, Corporation and the like.


If you're doing for Canada remember that not all letters are valid

These letters are invalid: D, F, I, O, Q, or U And the letters W and Z are not used as the first letter. Also some people use an optional space after the 3rd character.

Here is a regular expression for Canadian postal code:

new RegExp(/^[abceghjklmnprstvxy][0-9][abceghjklmnprstvwxyz]\s?[0-9][abceghjklmnprstvwxyz][0-9]$/i)

The last i makes it case insensitive.


Suggest you have a look at the USPS Address Information APIs. You can validate a zip and obtain standard formatted addresses. https://www.usps.com/business/web-tools-apis/address-information.htm


Here's a JavaScript function which validates a ZIP/postal code based on a country code. It allows somewhat liberal formatting. You could add cases for other countries as well. Note that the default case allows empty postal codes since not all countries use them.

function isValidPostalCode(postalCode, countryCode) {
    switch (countryCode) {
        case "US":
            postalCodeRegex = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/;
            break;
        case "CA":
            postalCodeRegex = /^([A-Z][0-9][A-Z])\s*([0-9][A-Z][0-9])$/;
            break;
        default:
            postalCodeRegex = /^(?:[A-Z0-9]+([- ]?[A-Z0-9]+)*)?$/;
    }
    return postalCodeRegex.test(postalCode);
}

FYI The second link referring to vanity ZIP codes appears to have been an April Fool's joke.