JavaScripts :: Detectors :: Zip Code Validator
This javascript checks the length of a zip or post code entered into a form and if the length is equal to 9 numeric characters will then format it with a hyphen inserted after the 4th character. Suitable for validating US postal codes only. Users may enter alpha characters or non numeric characters in the zip code such as hyphens and or spaces. The Javascript will remove all non numeric charcters and return the formated zip code.
Simply copy the function to your web document, then call the function in your form validation.
The Script
<script>
<!--
/* Copyright http://www.perlscriptsjavascripts.com
Free and commercial Perl and JavaScripts */
function checkZip(z){
if(document.images){
z.value = z.value.replace(/\D+/, "");
}
if(z.value.length != 5 && z.value.length != 9){
alert("Whoops, please check your zip code");
if(document.all || document.getElementById){
z.style.background = "yellow";
}
z.focus();
return (false);
}
if(z.value.length > 5){
z.value = z.value.substr(0,5) + "-" + z.value.substr(5);
}
return (z.value);
}
// -->
</script>
Usage
Inside your existing form validation script, you'd use the following code to call the zip code validation function. If the zip code entered by the user has an invalid length after non numeric characters are removed, and alert message will pop up. Here is an example form validation script and it's form.
<script>
<!--
function checkForm(f){
if(!checkZip(f.zip)){
return false;
} else {
f.zip.value = checkZip(f.zip);
}
}
// -->
</script>
<form onsubmit="return checkForm(this);">
<input type="Text" name="zip">
<input type="Submit" value="Check">
</form>
The code below combines both functions and the sample form so you may test the script in real time. Simply copy and paste all code in to any web page.
|