Efficient regex for Canadian postal code function

前端 未结 7 1423
说谎
说谎 2020-12-24 01:57
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 )          


        
7条回答
  •  独厮守ぢ
    2020-12-24 02:15

    You have a problem with the regex StatsCan has posted the rules for what is a valid Canadian postal code:

    The postal code is a six-character code defined and maintained by Canada Post Corporation (CPC) for the purpose of sorting and delivering mail. The characters are arranged in the form ‘ANA NAN’, where ‘A’ represents an alphabetic character and ‘N’ represents a numeric character (e.g., K1A 0T6). The postal code uses 18 alphabetic characters and 10 numeric characters. Postal codes do not include the letters D, F, I, O, Q or U, and the first position also does not make use of the letters W or Z.

    The regex should be if you wanted it strict.

    /^[ABCEGHJ-NPRSTVXY][0-9][ABCEGHJ-NPRSTV-Z] [0-9][ABCEGHJ-NPRSTV-Z][0-9]$/
    

    Also \d means number not necessarily 0-9 there may be the one errant browser that treats it as any number in unicode space which would likely cause issues for you downstream.

    from: https://trajano.net/2017/05/canadian-postal-code-validation/

提交回复
热议问题