jQuery and ASP.NET

July 18, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Validate US Zip Code using JavaScript"
  1. Stela James said...
    July 19, 2010 12:10 AM

    Thanks for code!
    home jobs

  2. Relationals said...
    July 23, 2010 10:08 AM

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

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions