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
Popularity: 14% [?]
If you enjoyed this post, make sure you subscribe to my RSS feed!Related posts:
- Validate U.S Phone Numbers using JavaScript Regular expression.
- Validate email address using JavaScript regular expression
- How to validate Social Security Number (SSN) using JavaScript Regular Expressions
- How to validate date using Java regular expression
- Ultimate Java Regular Expression to validate any email address.







Very helpful code, thanks!