One Regular Expression to validate US and Canada ZIP / Postal Code

前端 未结 2 2186
小鲜肉
小鲜肉 2021-02-20 17:33

I am developing a stationery program. Customers have choice to pick their region either US or Canada. When they enter address they have to enter ZIP/Postal code. I am trying to

2条回答
  •  清酒与你
    2021-02-20 17:51

    Not knowing what language you're using, I will not use any abbreviations for character classes:

    ^[0-9]{5}$|^[A-Z][0-9][A-Z] ?[0-9][A-Z][0-9]$
    

    Depending on your language, you might be able to abbreviate this to

    ^([0-9]{5}|[A-Z][0-9][A-Z] ?[0-9][A-Z][0-9])$
    

    or

    ^(\d{5}|[A-Z]\d[A-Z] ?\d[A-Z]\d)$
    

    To support ZIP+4:

    ^(\d{5}(-\d{4})?|[A-Z]\d[A-Z] ?\d[A-Z]\d)$
    

    And if you want to get really picky about your Canada codes:

    ^(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$
    

提交回复
热议问题