How to validate zip code in java if the zip code pattern changes dynamically?

ashishjmeshram picture ashishjmeshram · Nov 21, 2011 · Viewed 8.3k times · Source

I need to validate the zip code in java. I have googled and there are many regular expressions.

The problem I have is the required zip code pattern may change from some admin settings page. Like at some instance, we may need users to enter zip code in format XXX - XXX or may be (XXXXXX) etc.

In some case zip code can consist of numbers only and in some cases alpha numeric.

Please help.

Answer

Ted Hopp picture Ted Hopp · Nov 21, 2011

Unfortunately, there is no good localization support for postal addresses, including postal codes (aka zip codes). This blog post (about a year old, but still, unfortunately, relevant) describes the sorry state of postal address validation. In the U.S., the postal service offers their Address Validation API; a web-based protocol. The only other tool I know of is an Android library called libaddressinput. The project summary says that while the UI is Android-specific, the back end can be reused.