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

Share:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Twitthis
This entry was posted in JavaScript, Syndicated. Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree