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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With