Last updated: Mar 7, 2024
Reading timeยท5 min
To validate a zip code:
RegExp.test()
method to check for a regular expression.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
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.
For example, the following US zip codes are valid:
We passed a regular expression to the RegExp.test()
method.
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.
|
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:
If either condition is met, the regular expression matches and the
RegExp.test()
method returns true
, otherwise, false
is returned.
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.
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.
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.
<!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>
And here is the related JavaScript code.
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); }
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.
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 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.
You can also use a different regular expression to validate a US zip code.
The following regex is a little more concise.
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
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.
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:
If your zip code might be of type number, use the String()
constructor to
convert it to a string before calling the isValidZipCode()
function.
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.
You can learn more about the related topics by checking out the following tutorials: