39

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.

benc
  • 1,381
  • 5
  • 31
  • 39
  • Your blog post states that "ZIP + 4 (10 digits)", after stating that a plain ZIP code is 5 digits. I have a hard time understanding the maths, here. – unwind Feb 13 '09 at 15:21
  • @unwind: ZIP+4 is actually 10 *characters*, not 10 *digits*. It's 9 digits, formatted as 12345-6789. The reference on that page to ZIP+4 being 10 digits is incorrect. – Dave Sherohman Feb 13 '09 at 15:44
  • good point, I'll clarify that. – benc Feb 13 '09 at 22:54
  • Referring to the article and the weird new type of ZIP code. My guess is that SHOE is just referring to the related numbers of your keypad on a phone... – Marijn Huizendveld May 15 '10 at 14:27
  • The letters appear to be literal, so a completely compliant validator would either allow characters, or possibly hardcode the only exception. I have not found additional information from the USPS to clarify this matter. – benc May 31 '10 at 05:55

13 Answers13

54

Javascript Regex Literal:

US Zip Codes: /(^\d{5}$)|(^\d{5}-\d{4}$)/

var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210");

Some countries use Postal Codes, which would fail this pattern.

Matt
  • 74,352
  • 26
  • 153
  • 180
keparo
  • 33,450
  • 13
  • 60
  • 66
26
function isValidUSZip(sZip) {
   return /^\d{5}(-\d{4})?$/.test(sZip);
}
Andrey Fedorov
  • 9,148
  • 20
  • 67
  • 99
6

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.

Mike Henry
  • 2,401
  • 1
  • 25
  • 34
  • I'm pretty sure that you are referring to the NPR story from 2004 (which I just found). The info in the 2nd link was from 2007, and I think one of the articles I read was actually from the USPS site (I didn't save every link). – benc Oct 02 '08 at 06:11
  • I'm surprised nobody has suggested making Canadian post code regexes case insensitive. One could easily convert lowercase input to upper before passing to wherever it's going. Think about the user experience! – gillytech Oct 22 '14 at 01:15
5

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.

Samer
  • 973
  • 1
  • 6
  • 15
3

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/

Sparky
  • 98,165
  • 25
  • 199
  • 285
Shogo Yahagi
  • 141
  • 1
  • 2
1

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.

1

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

Carl
  • 446
  • 2
  • 7
1

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

/\b\d{5}-\d{4}\b/
Awais Qarni
  • 17,492
  • 24
  • 75
  • 137
0

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.

Irfan
  • 7,029
  • 3
  • 42
  • 57
0

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.

0

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/

pal4life
  • 3,210
  • 5
  • 36
  • 57
-1

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.

Saif Khan
  • 18,402
  • 29
  • 102
  • 147
-1

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])$/

  • Are lower case letters allowed? I took a quick look in the wikipedia entry, and the examples appear to be all upper-case, but it was not stated explicitly. – benc Feb 18 '09 at 21:35