Efficient regex for Canadian postal code function
javascript, regex
Solution
User kind, postal code strict, most efficient format:
/^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i
Allows:
- h2t-1b8
- h2z 1b8
- H2Z1B8
Disallows:
- Z2T 1B8 (leading Z)
- H2T 1O3 (contains O)
Leading Z,W or to contain D, F, I, O, Q or U
Problem
``` var regex = /[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d/; var match = regex.exec(value); if (match){ if ( (value.indexOf("-") !== -1 || value.indexOf(" ") !== -1 ) && value.length() == 7 ) { return true; } else if ( (value.indexOf("-") == -1 || value.indexOf(" ") == -1 ) && value.length() == 6 ) { return true; } } else { return false; } ``` The regex looks for the pattern A0A 1B1. true tests: A0A 1B1 A0A-1B1 A0A1B1 A0A1B1C << problem child so I added a check for "-" or " " and then a check for length. Is there a regex, or more efficient method?