8

Possible Duplicate:
Canada postal code validation

I need javascript regex for validating Canadian postal/zip code. Canada's Postal Code format is 'A1A 1X1' or 'a1a1x1'. However it doesn't include the letters D, F, I, O, Q, or U.I found few here but those were in C#.

Community
  • 1
  • 1
DarknessBeginsHere
  • 592
  • 1
  • 5
  • 20

2 Answers2

16
function checkPostal(postal) {
    var regex = new RegExp(/^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$/i);
    if (regex.test(postal.value))
        return true;
    else return false;
}
DarknessBeginsHere
  • 592
  • 1
  • 5
  • 20
  • Might want to strip spaces to the left/right (or even in the middle). – Derek Schrock Oct 08 '12 at 00:36
  • Space in the middle is facultative so it does well the job. Just adjust the return values to true (first) and false (last). Then, be aware that this function tests regex on variable 'postal' 'value'. I reedited the third line as follows : if (regex.test(postal)) ...providing the value to the function directly. – guylabbe.ca Jul 09 '14 at 01:27
  • 1
    Be aware that the no usage of certain characters may change in time as new postal code would be needed. – Below the Radar Nov 18 '16 at 13:40
-2

As the exceptional words have nothing in common, the valid words should be written one by one.

[ABCEGHJKLMNPRSTVWXYZ]

Followed by a digit

\d

And this three times

{3}

Finally we add "i" for case-insensitive

var regex = /([ABCEGHJKLMNPRSTVWXYZ]\d){3}/i;
A. Matías Quezada
  • 1,886
  • 17
  • 34