US 5 and 9 Digits Zip Code Validation In Java Using Regular Expressions

ZIP codes are a system of postal codes used by the United States Postal Service (USPS) since 1963. The term ZIP, an acronym for Zone Improvement Plan, is properly written in capital letters and was chosen to suggest that the mail travels more efficiently, and therefore more quickly, when senders use the code in the postal address. The basic format consists of five decimal numerical digits. An extended ZIP+4 code, introduced in the 1980s, includes the five digits of the ZIP code, a hyphen, and four more digits that determine a more precise location than the ZIP code alone. The term ZIP code was originally registered as a servicemark (a type of trademark) by the U.S. Postal Service, but its registration has since expired. [Wikipedia / Creative Commons]

The following java class uses the regular expressions to validate the zip code. It also has tests for various sample valid and invalid zip codes.

package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * Last Modified on 2010/12/12
 * www.sanjaal.com/java
 * This class demonstrates the use of regular expressions to validate US Zip code.
 * It basically validates two rules:
 * - Zip code should have five digits initially.
 * - The last four digits along with the hyphen sign are optional and can be present or absent from the zip code.
 */
import java.util.regex.Pattern;

public class ZipcodeValidatorUS {
	/**
	 * Regular Expression to match the US Zip-Code
	 */
	static final String regex = "^\d{5}(-\d{4})?$";

	/**
	 * Testing the zip code validation with some sample zip codes
	 */
	public static void main(String args[]) {

		String mixedZips[] = { 	"50266-234A", "50266-2342", "5026A-2344",
								"5026A-234A", "50266", "230" };

		int index = 0;
		boolean isMatch = false;
		while (index < mixedZips.length) {
			isMatch = isAValidZipCode(mixedZips[index]);
			System.out.println("Zip " + mixedZips[index] + " - "
					+ (isMatch ? "Valid" : "Invalid"));
			index++;
		}

	}
	
	/**
	 * This method returns true if the parameter string is a valid zip code
	 */
	public static boolean isAValidZipCode(String zip) {
		return Pattern.matches(regex, zip);
	}

}

The following is the output of this program:

Zip 50266-234A - Invalid
Zip 50266-2342 - Valid
Zip 5026A-2344 - Invalid
Zip 5026A-234A - Invalid
Zip 50266 - Valid
Zip 230 - Invalid