Making Sure That A User Can't Submit Less Than 5 Numbers For Zip Code In A Javascript Form
Solution 1:
I'd suggest embracing HTML5
<form name="reg" onSubmit="return formValidation();">
<p>Zip Code:
<input type="text"id="zip" pattern="\d{5}" maxlength="5" name="zip" required="required" />
</p>
<input type="submit"id="submitbutton" name="submitbutton" value="Submit" />
<div id="msg"></div>
</form>
Solution 2:
You want zip.value.length
, not zip.numbers
.
You can also do the whole thing with the regex:
var numbers = /^\d{5}$/;
if(zip.value.match(numbers))
{
document.getElementById("msg").innerHTML=("OK ✓");
msg.style.color="green";
}
else
{
msg.innerHTML=("Numbers only please.");
msg.style.color="red";
}
Solution 3:
I think the other answers cover the essence of your JS question but not really the Data Quality aspect as I don't think you really should be validating a zip in this way.
You're certainly taking the correct approach by trying to ensure the quality of the user input - but just checking for 5 numbers might not be enough.
There of tens of thousands of addresses where a 4 or 3 digit zip code should be considered valid input - where the Zip starts with one or two 0's. Some examples include:
- Bridgeton, NJ 08302
- Holtsville, NY 00544
- Adjuntas, PR 00601 (All zip codes in Puerto Rico start with 00)
- Christiansted, VI 00821
Users frequently omit the leading 00 / 0 and that should really be allowed in your form - they may find it an unpleasant distraction from your workflow if users are getting the handy inline validation message telling them they are incorrect when they know they are not.
The second possible flaw (again depending upon your workflow) is that people may enter the zip+4 too. You probably don't want to limit them to just the 5 when you may be able to get the full 9.
This means that your JS test would have to be updated to allow for the combinations, but would lead to a more robust final product. At a minimum, I'd suggest that as part of your form you include example zip codes (placeholder text or similar) which include the '00' case so users know what is expected. To allow for the optional +4 to be entered, update your regex to:
var numbers = ^\d{5}(-\d{4})?$;
if(zip.value.match(numbers))
{
....
}
else
{
...
}
And finally the ultimate way to ensure that you are catching the correct zip code and that they are correctly associated with an address is to validate the whole thing (regardless of the length of the zip). These validation services which you either make and maintain yourself or use a third party (such my company - http://www.qas.com/products/on-demand-address-validation.htm) can speed the capture of an address and ensure it is valid - coping with 3, 4 or 5 digit zips, enhancing the address with missing +4, correcting typos in the zip or other address elements.
Hope that helps and good luck!
Al.
Post a Comment for "Making Sure That A User Can't Submit Less Than 5 Numbers For Zip Code In A Javascript Form"