tags:

views:

226

answers:

5

I need a a regular expression to validate Zipcode or postcode - it must be 8 characters alphanumeric field i.e allow A-Z, a-z, or 0-9.

Thanks.

+8  A: 
^[a-zA-Z0-9]{8}$

This will also work, but usually allows underscores: ^\w{8}$

Update:

To allow free spaces within the string (for simplicity, this allows extra spaces on the end of the string, but not the beginning):

^([a-zA-Z0-9]\s*){8}$

This allows free spaces, hyphens and (back)?slashed, which are common in zip codes:

^([a-zA-Z0-9][\s\\/-]*){8}$
Kobi
^[a-zA-Z0-9]{8}$ this works but does not allow spaces . How can I allow for spaces ???? thanks
dylan7
A: 

You cant, because not all number patterns that satisfy a zip code format are valid zip codes.

mP
But: strings that don't match this patters are **definitely not zip codes**. You'll may have to verify that in some point, but it is wise to validate the format before you make an expensive query against a list of all real zip-codes...
Kobi
none of the reg expression seems to work - not sure , the spec says allow for alphanumeric characters which includes spaces but not special cahracters
dylan7
A: 

I would try to validate zip/postal codes in conjunction with the country code - if your validation framework supports this kind of custom validation. It's going to lead to more accurate validation especially if many of your customers are from a particular country.

For instance i check for country code first and if it is US I can be more specific :

   if (countryCode == "US") {

      regex = "^\d{5}([\-]\d{4})?$";    // trim string first
   }
   else {

       // see other answers!
   }

(of course this applies to any country, such as UK where postal codes are a fixed format)

Simon_Weaver
A: 

If you are interested in validating addresses around the world, check out http://intlmailaddress.com. It has postal address formats, postal code formats and phone formats from 246 countries. Region names, (like state, province, emirate, sheng, etc.)

Douglas Hahn
A: 

Validating the format of a code without validating its content is stopping short unnecessarily. See http://semaphorecorp.com/cgi/zip5.html for examples.

joe snyder