开发者

How to create a regular expression to validate zip- and postal codes?

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.


^[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}$


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


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)


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜