Skip to main content

How to Validate a US ZIP Code in JavaScript

When working with forms that collect address information, validating the format of a US ZIP code is a common requirement. A valid US ZIP code can be either a 5-digit code (e.g., "90210") or the extended ZIP+4 format, which consists of 5 digits, a hyphen, and 4 more digits (e.g., "90210-1234").

This guide will teach you the most effective and concise way to validate a US ZIP code using a single regular expression and the RegExp.prototype.test() method.

The most efficient and readable way to validate a ZIP code is to use a regular expression that accounts for both the 5-digit and the ZIP+4 formats.

Problem: you need a function that returns true for valid ZIP code formats and false for all other strings.

// Problem: Create a function to validate these strings.
isValidZip('90210'); // Should be true
isValidZip('90210-1234'); // Should be true
isValidZip('9021'); // Should be false
isValidZip('90210-123'); // Should be false
isValidZip('abcde'); // Should be false

Solution: this single, concise regular expression handles both valid formats.

/**
* Validates a US ZIP code (5 digits or ZIP+4 format).
* @param {string} zipCode The ZIP code string to validate.
* @returns {boolean} True if the ZIP code is valid, false otherwise.
*/
function isValidZipCode(zipCode) {
let zipCodePattern = /^\d{5}(-\d{4})?$/;
return zipCodePattern.test(zipCode);
}

// Example Usage:
console.log(isValidZipCode('90210')); // # Output: true
console.log(isValidZipCode('90210-1234')); // # Output: true
console.log(isValidZipCode('90210-123')); // # Output: false
console.log(isValidZipCode('abcde')); // # Output: false
note

The test() method of a regular expression returns true if the pattern is found in the string, and false otherwise.

The Regular Expression Explained

The regular expression /^\d{5}(-\d{4})?$/ is the key to this solution. Let's break it down:

  • / ... /: The delimiters that mark the beginning and end of the regular expression pattern.
  • ^: An "anchor" that asserts that the pattern must start at the beginning of the string.
  • \d{5}:
    • \d: A "metacharacter" that matches any digit (0-9).
    • {5}: A "quantifier" that matches the preceding token (\d) exactly 5 times.
  • (...)?: This is an optional group.
    • (...): The parentheses group the sub-pattern together.
    • ?: A quantifier that matches the preceding token (the group) zero or one time.
    • -\d{4}: Inside the group, this matches a literal hyphen (-) followed by exactly 4 digits.
  • $: An "anchor" that asserts that the pattern must end at the end of the string.

So, /^\d{5}(-\d{4})?$/ translates to: "The string must start with exactly 5 digits, optionally followed by a group consisting of a hyphen and 4 more digits, and then the string must end."

How to Handle Numeric Input

The test() method expects a string argument. If your ZIP code is stored as a number, you must first convert it to a string.

let zipCodeNumber = 90210;

// Convert the number to a string before validating.
let isValid = isValidZipCode(String(zipCodeNumber));

console.log(isValid); // # Output: true

Practical Example: Validating a Form Input Field

This is a classic use case. The script listens for the submit event on a form and validates the ZIP code input before allowing the form to proceed.

HTML:

<form id="address-form">
<label for="zip-input">ZIP Code:</label>
<input type="text" id="zip-input" name="zip">
<button type="submit">Submit</button>
<p id="error-message" style="color: red;"></p>
</form>

JavaScript:

function isValidZipCode(zipCode) {
let zipCodePattern = /^\d{5}(-\d{4})?$/;
return zipCodePattern.test(zipCode);
}

let form = document.getElementById('address-form');
let zipInput = document.getElementById('zip-input');
let errorMessage = document.getElementById('error-message');

form.addEventListener('submit', (event) => {
// Validate the ZIP code value
if (!isValidZipCode(zipInput.value)) {
// If invalid, prevent the form from submitting and show an error.
event.preventDefault();
errorMessage.textContent = 'Please enter a valid 5-digit or ZIP+4 code.';
} else {
// If valid, clear any previous error message.
errorMessage.textContent = '';
console.log('Form submitted with valid ZIP code.');
}
});

Conclusion

Validating a US ZIP code is a straightforward task when you use a well-crafted regular expression.

  • The recommended best practice is to use the test() method with the regex /^\d{5}(-\d{4})?$/.
  • This single pattern correctly validates both the 5-digit and ZIP+4 formats.
  • Always ensure the value you are testing is a string. If you have a number, convert it first with String().