Maybe a better solution would be to strip all non-numeric characters of the phone number for validation so that you're just left with a string of numbers.
Regular expressions can break easily unless you are very strict with their input and since phone numbers vary so greatly around the world, this way will allow you to support any phone number without having to create a very complicated regular expression.
You can just use a simple method like this:
- (NSString *)sanitizePhoneNumberString:(NSString *)phoneNumber {
NSCharacterSet *illegalCharacters = [NSCharacterSet characterSetWithCharactersInString:@" +()-"];
return [[phoneNumber componentsSeparatedByCharactersInSet:illegalCharacters] componentsJoinedByString:@""];
}
So instead of +1 (555) 123-4567
You'd just compare 15551234567
. If you're storing this in a database, you probably want to control the format anyways for showing on the UI and integer comparison is faster than string comparison for large data sets so you can just store the [sanitizedPhoneNumber intValue];
in the database as an NSNumber
Another method using a simple Regex to allow only the numbers 0-9 (source):
- (NSString *)sanitizePhoneNumberString:(NSString *)phoneNumber {
return [phoneNumber stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [phoneNumber length])];
}