Validate Zip code using JavaScript Regular expression

Zip Code

Zip Code

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);


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


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

If you enjoyed this post, make sure you subscribe to my RSS feed!

12 Thoughts on “Validate Zip code using JavaScript Regular expression

  1. Very helpful code, thanks!

  2. Pingback: Validate U.S Phone Numbers using JavaScript Regular expression.

  3. Precisely what I needed!! Thanks a bunch…

  4. sachin on July 11, 2011 at 3:23 am said:

    Exactly what i m needed , thanks a ton

  5. Great post I must say. Simple but yet interesting. Wonderful work!

  6. noushad on November 11, 2011 at 2:15 am said:

    simple and good

  7. thanks yar

  8. Pingback: Zipcode regex | Mdigspr31

  9. this should also work if you want it even more succinct!

    var zipCodePattern = /^\d{5}(-\d{4})?$/;

    for those that are new to regex, the ‘?’ means “match either 0 or 1 of the thing preceding it,” which, in this case, is the optional dash and four digits

  10. Hey there! Quick question that’s entirely off topic.
    Do you know how to make your site mobile friendly? My web
    site looks weird when browsing from my iphone.
    I’m trying to find a template or plugin that might be able to
    fix this issue. If you have any recommendations, please share.

  11. This means that many coaches aare still operating as if the training methods used in the Soviet Union in the 1970’s
    are state of the art. That inquiry could be expanded because
    in that location are no longer gratuitous online football games do work.
    At the same time, it also allows great control over the team and individual players throughout the match.

    Also visit my blog … Cheats Topp Eleven (Maybell)

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation