How to check Zipcode for USA or Canada in iOS?

I want to know if there is a way to check US or Zipcode in Canada? I tried to use regex. As for USA

- (BOOL)validateZip:(NSString *)candidate { NSString *emailRegex = @"(^{5}(-{4})?$)|(^[ABCEGHJKLMNPRSTVXY][AZ][- ]*[AZ]$)"; NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; return [emailTest evaluateWithObject:candidate]; } 

but it does not work. Please, any body has any idea regarding this confirmation. Should any rest api exist for checking?

+4
source share
2 answers

For the USA, you have quantifiers ( {5} , {4} ? ) Correctly, but you forgot to indicate exactly what you are quantifying. Do you want to:

 (^[0-9]{5}(-[0-9]{4})?$) 

In Canada, according to Wikipedia, the format is A0A 0A0 , so I would do:

 (^[a-zA-Z][0-9][a-zA-Z][- ]*[0-9][a-zA-Z][0-9]$) 

Now I would write a complete expression like this with case sensitivity turned on:

 @"^(\\d{5}(-\\d{4})?|[az]\\d[az][- ]*\\d[az]\\d)$" 

Honestly, I'm really not familiar with Objective-C or iOS, and unfortunately, I have not tested the above. However, I have previously seen that such messages mention NSRegularExpression , which is missing from your code but may not be needed. Take a look at other examples to see what other simple mistakes you could make. Good luck.

+12
source

We used this, but only for UK zip codes. See @ Acheong87's answer to change the regex according to your criteria and other good answers.

 NSString *postcodeRegex = @"[AZ]{1,2}[0-9R][0-9A-Z]?([0-9][ABD-HJLNP-UW-Z]{2}";//WITH SPACES NSPredict *postcodeValidate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", postcodeRegex]; if ([postcodeValidate evaluateWithObject:postcodeField.text] == YES) { NSLog (@"Postcode is Valid"); } else { NSLog (@"Postcode is Invalid"); } 

I suggest you check the regex first using this great tool http://www.regexr.com

EDIT

The current regex does not support spaces in the zip code after further testing. This will fix this problem.

 NSString *postcodeRegex = @"[AZ]{1,2}[0-9R][0-9A-Z]?(\s|)([0-9][ABD-HJLNP-UW-Z]{2}";//WITH SPACES 
+1
source

Source: https://habr.com/ru/post/1439820/


All Articles