4

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?

Ankit Vyas
  • 7,507
  • 13
  • 56
  • 89

2 Answers2

12

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.

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
1

We used this but its only for UK Postcodes. See @acheong87 answer to alter the regex to fit your criteria and other good answers.

NSString *postcodeRegex = @"[A-Z]{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 advise you test the regex first using this great tool http://www.regexr.com

EDIT

Current regex does not support spaces in postcode after further testing. This will fix that issue.

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