Validate Zip code using JavaScript Regular expression
Feb 18
Javascript, Most Popular Posts Javascript, RegEx, Regular Expression 7 Comments
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
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.




May 30, 2009 @ 15:47:33
Very helpful code, thanks!
Apr 28, 2011 @ 05:09:08
Precisely what I needed!! Thanks a bunch…
Jul 11, 2011 @ 03:23:49
Exactly what i m needed , thanks a ton
Oct 01, 2011 @ 23:01:17
Great post I must say. Simple but yet interesting. Wonderful work!
Nov 11, 2011 @ 02:15:57
simple and good
Dec 27, 2011 @ 07:55:50
thanks yar