Sometimes, we want to validate ZIP code (US postal code) with JavaScript.
In this article, we’ll look at how to validate ZIP code (US postal code) with JavaScript.
Validate ZIP Code (US Postal Code) with JavaScript
To validate ZIP code (US postal code) with JavaScript, we can use a regex that matches 5 digit numbers or 5 digit numbers with a 4 digit number separated by a dash.
For instance, we can write:
const isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210");
console.log(isValidZip)
to match 5 digit numbers with (^\d{5}$)
.
And we match 5 digit numbers with a dash and 4 digit number after it with (^\d{5}-\d{4}$)
.
We match both by joining both patterns with |
.
Then we call test
with a string to check if the string matches the regex pattern.
Therefore, from the console log, we should see that isValidZip
is true
since it’s a 5 digit number.
Conclusion
To validate ZIP code (US postal code) with JavaScript, we can use a regex that matches 5 digit numbers or 5 digit numbers with a 4 digit number separated by a dash.