Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate Zipcode for US or Canada in iOS?

I want to know that is there any way to validate the the zipcode of US or Zipcode of Canada?I have tried to use regex. Like for US

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

    return [emailTest evaluateWithObject:candidate];   
}

but it's not working.Please any body have any idea regarding this validation.if any rest api is there for the validation?Please guide me if possible?

like image 568
Ankit Vyas Avatar asked Dec 11 '22 21:12

Ankit Vyas


1 Answers

For the US, you have the quantifiers ({5}, {4}, ?) correct but forgot to specify exactly what you're quantifying. You want:

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

For 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'd write the complete expression like this, with case insensitivity enabled:

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

Frankly, I'm not actually familiar with Objective C or iOS, and sadly I haven't tested the above. However, previously I've seen such posts mention NSRegularExpression, which is missing in your code, but perhaps isn't necessary. Take a look at others' examples to see what other simple errors you might be making. Good luck.

like image 198
slackwing Avatar answered Jan 05 '23 00:01

slackwing