iOS: Valid zip code check

主宰稳场 提交于 2019-12-01 11:26:57

^[ABCEGHJKLMNPRSTVXY]\d[A-Z][- ]*\d[A-Z]\d$

Matches Canadian PostalCode formats with or without spaces (e.g., "T2X 1V4" or "T2X1V4")


^\d{5}(-\d{4})?$

Matches all US format ZIP code formats (e.g., "94105-0011" or "94105")


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

Matches US or Canadian codes in above formats.


UK codes are more complicated than you think: http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom

I suggest you don't do this. I've seen many websites that try to enforce zipcodes, but I've never seen one get it right. Even the name zipcode is specific to the US.

In other words:

- (BOOL)isValidZipCode: (NSString *)zip {
    return YES;
}

I was originally going to write [zip length] > 0, but of course even that isn't guaranteed.

Each country that uses postcodes/zip codes usually has their own format. You are going to be hard-pressed to find a regular expression that matches any worldwide code!

You're better off adding a country picker that determines the regular expression (if any) to be used to validate the zip code.

As an aside, the postcode you have given as a UK example is not correct. A decent UK regex is:

^(^gir\\s0aa$)|(^[a-pr-uwyz]((\\d{1,2})|([a-hk-y]\\d{1,2})|(\\d[a-hjks-uw])|([a-hk-y]\\d[abehmnprv-y]))\\s\\d[abd-hjlnp-uw-z]{2}$)$
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!