Validate US Zip Code using JavaScript

Here’s how to validate US Zip code using JavaScript. We will be using a Regular Expression to do so.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Validate US Zip Code in JavaScript</title>
<
script type="text/javascript">
function
IsValidZipCode(zip) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zip);
if (isValid)
alert('Valid ZipCode');
else {
alert('Invalid ZipCode');
}
}
</script>
</
head>

<
body>
<
form>
<
input id="txtZip" name="zip" type="text" /><br />
<
input id="Button1" type="submit" value="Validate"
onclick="IsValidZipCode(this.form.zip.value)" />
</form>
</
body>
</
html>

The code above validates a US zip code based on both the five digit (12345) as well as nine-digit (12345-1234 ) schemes.

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

6 comments:

Stela James said...

Thanks for code!
home jobs

Relationals said...

Nice, but it doesn't validate the actual zip code, just the xxxxx-xxxx.
PaaS for ISVs

Unknown said...

Hi Excellent.. But it is not validating..
just try with /\d{5}-\d{4}$|^\d{5}$/.test(zip)

Unknown said...

i made a slightly change and work for my

function ValidateUSZipCode(zipcode)
{
var zipcodeformat = /^[0-9]{5}(?:-[0-9]{4})?$/;

if(zipcode.match(zipcodeformat))
{
console.log("correct zip");
}
else
{
console.log("incorrect zip");
return false;
}
}

thanks!!

Unknown said...

i made a slightly change and work for my

function ValidateUSZipCode(zipcode)
{
var zipcodeformat = /^[0-9]{5}(?:-[0-9]{4})?$/;

if(zipcode.match(zipcodeformat))
{
console.log("correct zip");
}
else
{
console.log("incorrect zip");
return false;
}
}

i hope work for you!!

Unknown said...

How could i enter certain zip codes and recognize only those for valid ?
thank you in advance