Reputation: 3615
I am trying to validate a Postal Code for Canada using Regular Expressions, but I would like to test each character as it is entered rather than wait until the user submits the form.
All of the examples I have found so far (including this one), seem to only validate the entire user entry rather than each character as it is entered.
This is what I am using so far, but it only works for the entire user entry, not on each character:
function validate(myform) {
if (myform.zip.value == "" || myform.zip.value == null || myform.zip.value == "Postal Code" || myform.zip.value.length > 7 ) {
alert("Please fill in field Postal Code. You should only enter 7 characters");
myform.zip.focus();
return false;
}
return okNumber(myform);
}
function okNumber(myform) {
var regex = /^[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$/;
if (regex.test(myform.zip.value) == false) {
alert("Input Valid Postal Code");
myform.zip.focus();
return false;
}
return true;
}
Does anyone have any examples of how to validate a Postal Code as each character is entered?
Upvotes: 0
Views: 230
Reputation: 20664
You could write the regex as a series of alternatives which match a partial Postal Code of one character, of two characters, etc, up to the complete Postal Code, but I'm not sure whether a regex is the right way to validate a Postal Code anyway.
Upvotes: 0