Zip Code (US Postal Code) validation in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
5 min

banner

# Table of Contents

  1. Zip Code (US Postal Code) validation in JavaScript
  2. Zip code validation in an HTML form in the Browser
  3. Using a different regular expression to validate a US Zip Code

# Zip Code (US Postal Code) validation in JavaScript

To validate a zip code:

  1. Use the RegExp.test() method to check for a regular expression.
  2. The regular expression should check if the value consists of 5 digits or 5 digits followed by a hyphen and 4 digits.
  3. If the condition is met, the zip code is valid.
index.js
function isValidZipCode(zipCode) { return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zipCode); } console.log(isValidZipCode('11101')); // ๐Ÿ‘‰๏ธ true console.log(isValidZipCode('30305')); // ๐Ÿ‘‰๏ธ true console.log(isValidZipCode('21043-4012')); // ๐Ÿ‘‰๏ธ true console.log(isValidZipCode('33134-4094')); // ๐Ÿ‘‰๏ธ true console.log(isValidZipCode('1234abc')); // ๐Ÿ‘‰๏ธ false console.log(isValidZipCode('1.2.3.4')); // ๐Ÿ‘‰๏ธ false console.log(isValidZipCode('')); // ๐Ÿ‘‰๏ธ false

zip code validation in javascript

The code for this article is available on GitHub

The isValidZipCode() function takes a string as a parameter and returns true if the string is a valid zip code and false otherwise.

The RegExp.test() method checks if the regular expression is matched in the string and returns true if it is and false if it isn't.

  • previously, the basic format of a zip code consisted of 5 digits.
  • in 1983, an extended ZIP+4 code was introduced.
  • the extended ZIP+4 code includes the 5 digits of the ZIP code, followed by a hyphen and 4 digits that identify a more specific location.

For example, the following US zip codes are valid:

  • 11220
  • 45202
  • 23223
  • 11220-4134
  • 11220-9831
  • 11220-1728

We passed a regular expression to the RegExp.test() method.

index.js
function isValidZipCode(zipCode) { return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zipCode); }

The forward slashes / / mark the beginning and end of the regular expression.

The caret ^ matches the beginning of the input and the dollar sign $ matches the end of the input.

The \d character matches any digit from 0 to 9.

The X{n} syntax matches exactly n occurrences of X.

In this case, the first part of the regular expression matches exactly 5 digits.

The pipe | means "or". In other words, "try to match the regex in the first set of parentheses or the regex in the second".

The second set of parentheses matches 5 digits that are followed by a hyphen and 4 digits.

In its entirety, the regular expression matches:

  • a string that consists of 5 digits
  • or a string that starts with 5 digits and is followed by a hyphen and 4 digits

If either condition is met, the regular expression matches and the RegExp.test() method returns true, otherwise, false is returned.

index.js
function isValidZipCode(zipCode) { return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zipCode); } if (isValidZipCode('11101')) { // ๐Ÿ‘‡๏ธ this runs console.log('The value is a valid US Zip code'); } else { console.log('The value is NOT a valid US Zip code'); }

If you have the zip code stored as an integer, use the String() constructor to convert it to a string.

index.js
function isValidZipCode(zipCode) { return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zipCode); } const postCode = 11101; if (isValidZipCode(String(postCode))) { // ๐Ÿ‘‡๏ธ this runs console.log('The value is a valid US Zip code'); } else { console.log('The value is NOT a valid US Zip code'); }

The RegExp.test() method takes a string, so we have to make sure to call it with one.

# Zip code validation in an HTML form in the Browser

Let's look at a simple example of using the function from the previous subheading to validate a US zip code taken from user input.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <form> <input type="text" id="zip-code" name="zip-code" /> <button id="btn" type="submit">Validate Zipcode</button> </form> <h2 id="validation-message"></h2> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const btn = document.getElementById('btn'); const zipCodeInput = document.getElementById('zip-code'); const validationMessage = document.getElementById( 'validation-message', ); btn.addEventListener('click', event => { event.preventDefault(); if (isValidZipCode(zipCodeInput.value)) { console.log('The zip code is valid'); validationMessage.innerText = 'The zip code is valid'; } else { console.log('The zip code is NOT valid'); validationMessage.innerText = 'The zip code is NOT valid'; } }); function isValidZipCode(zipCode) { return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zipCode); }

validate us zip code using html form

The code for this article is available on GitHub

The form is quite simple and consists of an input field that has a type of text and a button element with type set to submit.

We added a click event listener to the button element, so every time it's clicked, the supplied event handler function is invoked.

We first called the event.preventDefault() method to prevent the default behavior of the browser to refresh the page when the form is submitted.

index.js
btn.addEventListener('click', event => { event.preventDefault(); if (isValidZipCode(zipCodeInput.value)) { console.log('The zip code is valid'); validationMessage.innerText = 'The zip code is valid'; } else { console.log('The zip code is NOT valid'); validationMessage.innerText = 'The zip code is NOT valid'; } });
The code for this article is available on GitHub

The benefit of using a form and not a basic input field is that the user can submit the form when they press the Enter key.

If you have an unrelated input field and a button element, the user has to manually click on the button to trigger the click event.

The if statement uses the isValidZipCode() function to check if the value of the input element is a valid US zip code.

If the condition is met, we update the innerText of the validation message element.

If the supplied value is not a valid US zip code, we print a message to the console and update the innerText of the validation message element.

# Using a different regular expression to validate a US Zip Code

You can also use a different regular expression to validate a US zip code.

The following regex is a little more concise.

index.js
function isValidZipCode(zipCode) { return /^\d{5}(-\d{4})?$/.test(zipCode); } console.log(isValidZipCode('11101')); // ๐Ÿ‘‰๏ธ true console.log(isValidZipCode('30305')); // ๐Ÿ‘‰๏ธ true console.log(isValidZipCode('21043-4012')); // ๐Ÿ‘‰๏ธ true console.log(isValidZipCode('33134-4094')); // ๐Ÿ‘‰๏ธ true console.log(isValidZipCode('1234abc')); // ๐Ÿ‘‰๏ธ false console.log(isValidZipCode('1.2.3.4')); // ๐Ÿ‘‰๏ธ false console.log(isValidZipCode('')); // ๐Ÿ‘‰๏ธ false

using different regex to validate zip code

The code for this article is available on GitHub

The regular expression achieves the same result.

The forward slashes / / mark the beginning and end of the regex.

The caret ^ matches the beginning of the input and the dollar sign $ matches the end of the input.

The \d character matches any digit from 0 to 9.

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

The X{n} syntax matches exactly n occurrences of X.

In other words, the regex matches 5 digits.

The part in the parentheses matches a hyphen and 4 digits.

The question mark ? matches the preceding item (the capital letters) 0 or 1 times.

In other words, the first 5 digits could or could not be followed by a hyphen and 4 digits for the string to produce a match.

In its entirety, the regular expression matches:

  • a string that consists of 5 digits
  • or a string that starts with 5 digits and is followed by a hyphen and 4 digits

If your zip code might be of type number, use the String() constructor to convert it to a string before calling the isValidZipCode() function.

index.js
function isValidZipCode(zipCode) { return /^\d{5}(-\d{4})?$/.test(zipCode); } const zipCode = 11101; if (isValidZipCode(String(zipCode))) { // ๐Ÿ‘‡๏ธ this runs console.log('The value is a valid US Zip code'); } else { console.log('The value is NOT a valid US Zip code'); }

If you ever need help reading a regular expression, check out this regular expression cheat sheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev