Validate Zip code using JavaScript Regular expression

Continuing with my series of JavaScript regular expression today we will see how easy it is to validate zip code using regular expression in JavaScript. Previously we talked about validating email and Social Security number using JS regex.

In today’s post, I’ll show you how to use JavaScript regular expression to validate zip code. Let me first show you the JS code.

function validateZipCode(elementValue){
    var zipCodePattern = /^\d{5}$|^\d{5}-\d{4}$/;
     return zipCodePattern.test(elementValue);
}

Explanation:

The argument to this method is the zip code you want to validate.

In the method body we define a variable (‘zipCodePattern’) and assign a regular expression to it.

ZipCode format: The regular expression for zip code is

/^\d{5}$|^\d{5}-\d{4}$/

This is quite a simple regular expression.

What we are saying here is that a valid zip code can either have 5 digits or 5 digits followed by an hyphen(-) and ends with four digits. So, zip codes 38980 and 83900-8789 will pass validation. However, 83900- or 839008789 will not pass our validation test.
If you don’t want to have a zip+4 format you can use /^\d{5}$/ as the regular expression to validate simple zip code.

Image credit:smcgee