ReynierPM
ReynierPM

Reputation: 18690

Restrictive RegEx for validate Canada postal code

I am trying to validate a Canada Postal Code and I saw several RegEx 1, 2 and many more but none of them works as should be. I am trying with this one:

/[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]/gmi

Which is not working good as you may see in this test there should only match the first line because postal code needs and it's mandatory 3AllowedChars_emptySpace_3AllowedChars, then having this, how do I restrict only 3 chars before the empty space and 3 after and of course having the valid chars for Canada postal code? Any help?

UPDATE

Based on the solution posted here is the fix:

/^[ABCEGHJKLMNPRSTVXY]\d[A-Za-z][ -]\d[A-Za-z]\d$/gmi

The problem is that ? before [ -] means optional and the empty space is not optional. You can test valid matches here

Upvotes: 0

Views: 565

Answers (1)

Pabs123
Pabs123

Reputation: 3435

If all you need is a regex for canada postal code, try this:

^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$

It should do exactly what you're looking for

Upvotes: 4

Related Questions