I have written a JavaScript to validate Canadian Postal Codes using regex.
However, it does not seem to be working:
If statement:
if (myform.zip.value == "" || myform.zip.value == null || myform.zip.value == "Postal Code" || myform.zip.value.length < 12 ) {
alert("Please fill in field Postal Code. You should only enter 7 characters");
myform.zip.focus();
return false;
}
Function:
function okNumber(myform) {
var regex = /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/;
if (regex.test(myform.zip.value) == false) {
alert("Input Valid Postal Code");
myform.zip.focus();
return false;
}
return true;
}
It doesn't work at all, although code is executing. When I run it, I get:
Please fill in field Postal Code. You should only enter 7 characters
An example valid postal code would be T2X 1V4
.
The postal code is a six-character uniformly structured, alphanumeric code in the form “ANA NAN” where “A” is an alphabetic character and “N” is a numeric character. Two segments make up a postal code: Forward Sortation Area (FSA) and Local Delivery Unit (LDU).
The postal code is composed of 3 sections. The first section is a region code consisting of an alphabet and an alphanumeric character. The second section is a 3-4 digit area code. The third section is an optional 4-digit code identifying the exact address.
Canada Post defines a postal code as follows: A six-character alphanumeric combination (ANA NAN) assigned to one or more postal addresses. The postal code is an integral part of every postal address in Canada and is required for the mechanised processing of mail.
A regex approach can validate the format of a Canadian postcode, but it's not sufficient to guarantee that the postcode actually exists.
For example: A9A 0A0
looks like a valid Canadian postcode, but the forward sortation area A9A
doesn't actually exist.
Are you sure you wouldn't rather do some kind of lookup against an official list of postcodes?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With