View Full Version : Validation for US and Canada zipcode help

07-07-2011, 08:05 PM
I have tried many different scripts Regex and different javascripts but nothing seems to work. The code I will send is about the closest I have gotton but it pops up a box whether it is valid or not. I just really know nothing about javascript to even know what to change. Please if someone has an answer or better method I would really appreciate it.

<script type="text/javascript">
function validZip(zip)
if (zip.match(/^[0-9]{5}$/)) {
return true;
if (zip.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/)) {
return true;
if (zip.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/)) {
return true;
alert('*** Please enter a valid zip code.');
return false;

<input name="ZIP" type="text" id="ZIP" size="6" maxlength="10" onChange="validZip('zip')"/>

low tech
07-08-2011, 07:11 AM

Validation for US and Canada zipcode help

US Zip code 5 or 5-4 digits--- I believe it was written by Philip M on this forum but I don't have the link to the page.

<title>US Zip code 5 or 5-4 digits</title>
<script type = "text/javascript">
function addHyphen() {
var z = document.getElementById("zipcode").value;
z = z.replace(/[^0-9-]/, "");
if (/^\d{6}/.test(z)) {
z = z.substring(0,5) + "-" + z.substring(5);
document.getElementById("zipcode").value = z;

function chkZip() {
var z = document.getElementById("zipcode").value;
if (!/^\d{5}(-\d{4})?$/.test(z)) {
alert ("Invalid zip code - please re-enter!");
document.getElementById("zipcode").value = "";
return false;

Zip Code <input type = "text" id = "zipcode" size = "10" maxlength = "10" onkeyup = "addHyphen()" onblur = "chkZip()">



Just realised this script doesn't deal with letters and the op needed that;(
But I'll leave this code here because someone may search for Validation for US and Canada zipcode
in the future and only need digits.

Old Pedant
07-08-2011, 09:48 PM
Your call to the function is bogus!

You are doing

which means that you are *ALWAYS* asking validZip to test to see if the *STRING* 'zip' matches one of the pattern.

Since "zip" would only match the pattern /^[A-Z][A-Z][A-Z]$/ (after you do the toUpperCase() on it) of course it doesn't match any of your three patterns.

*NOW* try doing:


You still have a bug in one of your RegExp's. You *think* you are allowing a period in the middle of the Canadian postal code: A1A.1A1 In actuality, the period means "match ANY character" so you would match A1A?1A1 or even A1AB1A1 or ...

You need to "escape" the period (force an actual period) by putting a \ in front of it.

Finally, the whole thing could be done much simpler:

function validZip( zip )
var zipre = /^(\d{5}|[A-Z]\d[A-Z]\.?\d[A-Z]\d)$/i;
if ( zipre.test( zip ) ) return true;
alert("Not a valid zip or postal code");
return false;