Validate Canadian Postal Code using regex

javascript, postal-code, regex, validation

Solution

this will work for all canadian postal codes..

^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$

Problem

I have written a JavaScript to validate Canadian Postal Codes using regex. However, it does not seem to be working: JavaScript 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; } ``` Problem 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`.

Original source