I have a script written in JavaScript to Validate Canadian Postal Codes using Regex, however it does not seem to be working. Here is the script:
If statement:
The first error is the last condition in your initial if statement. myform.zip.value.length < 12
should always be true, so this part of your code will always alert the message "Please fill in field Postal Code. You should only enter 7 characters"
and take focus back to the zip
field. Since a valid postal code has a maximum of 7 characters, this should be changed to myform.zip.value.length > 7
.
After making that correction, the postal code T2X 1V4
that you provided in the comments validates. However, the regular expression you used can be simplified (as was also mentioned in the comments). You can remove all instances of {1}
since they're redundant. You probably also meant to follow the space with a ?
instead of a *
. A ?
means that the previous character or expression can appear 0 or 1 time, while a *
means that it can appear 0 or more times. I think you want at most one space in your postal codes.
Here's the full working code that I tested this with:
JavaScript Regex Tester
One final note, usually when you see [A-Z]
in a regular expression it's worth at least considering whether it should be [A-Za-z]
to accept either upper or lower case letters. I don't know if this is the case for Canadian postal codes, but it usually is the case that most forms should accept either input and correct the case as needed.