ZIP Code Validation Regular Expression
A valid U.S. ZIP Code follows the format defined by the United States Postal Service (USPS). It can be either a 5-digit ZIP code (e.g., 12345) or a ZIP+4 code with an optional 4-digit extension (e.g., 12345-6789). This regex validates both formats according to USPS Publication 28. ZIP codes are a specialized type of number pattern.
Recommended Solution
Explanation
^- Start of the string.\d{5}- Exactly 5 digits for the basic ZIP code.(?:-\d{4})?- Optional group for ZIP+4: a hyphen followed by exactly 4 digits.$- End of the string.
Notes
- This regex validates the format of ZIP codes but does not verify if a ZIP code actually exists or is assigned to a location.
- ZIP codes range from 00501 to 99950, but this regex accepts any 5-digit combination for simplicity.
- The ZIP+4 extension provides more precise location information within a ZIP code area.
- For international postal codes, different patterns are needed (e.g., Canadian postal codes use the format A1A 1A1).
Implementation
Test Cases
| ZIP Code | Valid |
|---|---|
| 12345 | |
| 12345-6789 | |
| 90210 | |
| 00501 | |
| 99950-0001 | |
| 1234 | |
| 123456 | |
| 12345- | |
| 12345-678 | |
| 12345-67890 | |
| abcde | |
| 12 345 | |
| 12-345 | |
| (empty string) | |
| -1234 | |
| 12345-abcd |