/*
ValidZipCode - true for valid zip codes, false for invalid ones
*/
function ValidZipCode(ZipCode)
{
//Your zip code must contain 5 or 9 digits.
// 9 digit zip codes should contain no spaces and a
// hyphen before the last 4 digits.
var stringValue = new String(ZipCode);
var stringLength = stringValue.length;
if ((stringLength!=5)&&(stringLength!=9)&&(stringLength!=10))
{
return false;
}
if(stringLength==5)
{
for (var i = 0; i < stringLength; i++)
{
value = stringValue.charAt(i)
if (!((value >= 0) && (value <=9)))
{
return false;
}
}
}
if(stringLength==9)
{
for (var i = 0; i < stringLength; i++)
{
value = stringValue.charAt(i)
if (!((value >= 0) && (value <=9)))
{
return false;
}
}
}
if(stringLength==10)
{
var zip=stringValue.substring(0,5)
var symbol=stringValue.substring(5,6)
var plus4=stringValue.substring(6,10)
if(symbol!="-")
{
return false;
}
for (var i = 0; i < zip.length; i++)
{
value = zip.charAt(i)
if (!((value >= 0) && (value <=9)))
{
return false;
}
}
for (var i = 0; i < plus4.length; i++)
{
value = plus4.charAt(i)
if (!((value >= 0) && (value <=9)))
{
return false;
}
}
}
return true;
}
Programming tips, tricks and advice from Jonathan Leger, a seasoned professional programmer/analyst.
ASP.NET, VB.NET, Visual Basic, MS Access, MS SQL Server, PHP, MySQL, JavaScript and more!
Monday, July 19, 2004
JavaScript Function to Validate Zip codes (valid zipcode)
This function returns True if a Zipcode is a validly formatted U.S. Zip code, false if it is not.