0

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?

Community
  • 1
  • 1
DanielAttard
  • 3,467
  • 9
  • 55
  • 104
  • I'm sorry I'm not giving you an actual solution, just a suggestion. In this specific case where you need to validate a postal code, if you are going to implement your own parser (since you are going to check each character on your routine) it would be much better just to be sure the character is digit and the full length == 5 each time the handler gets called and doesn't allow to exceed the max expected length. So you need help on the javascript side and maybe you may add a tag on that domain. I had such a scenario..I used such technique already. Would need too much time to find it – Diego D Aug 05 '12 at 22:03

1 Answers1

0

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.

MRAB
  • 20,356
  • 6
  • 40
  • 33