Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c regex to check phone number [duplicate]

Possible Duplicate:
A comprehensive regex for phone number validation

How to validate a phone number (NSString *) in objective-c? Rules:

  • minimum 7 digits
  • maximum 10 digits
  • the first digit must be 2, 3, 5, 6, 8 or 9

Thanks

like image 449
ohho Avatar asked Jul 28 '10 02:07

ohho


4 Answers

You can use a regular expressions library (like RegexKit, etc), or you could use regular expressions through NSPredicate (a bit more obscure, but doesn't require third-party libraries). That would look something like this:

NSString *phoneNumber = ...;
NSString *phoneRegex = @"[235689][0-9]{6}([0-9]{3})?"; 
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex]; 
BOOL matches = [test evaluateWithObject:phoneNumber];

If you're on iPhone, then iOS 4 introduced NSRegularExpression, which would also work. The NSPredicate approach works on both Mac and iPhone (any version).

like image 87
Dave DeLong Avatar answered Nov 15 '22 06:11

Dave DeLong


Please don't use your own regex for the phone-number. Don't.

The format of phone numbers changes across the country, and your app might be used outside of your own country.

Instead, use what Apple provides, as Josh says. See here.

like image 23
Yuji Avatar answered Nov 15 '22 07:11

Yuji


For those searching for phone extraction, you can extract the phone numbers from a text, for example:

NSString *userBody = @"This is a text with 30612312232 my phone";
if (userBody != nil) {
    NSError *error = NULL;
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];
    NSArray *matches = [detector matchesInString:userBody options:0 range:NSMakeRange(0, [userBody length])];
    if (matches != nil) {
        for (NSTextCheckingResult *match in matches) {
            if ([match resultType] == NSTextCheckingTypePhoneNumber) {
                DbgLog(@"Found phone number %@", [match phoneNumber]);
            }
        }
    }
}

`

like image 11
Rafael Sanches Avatar answered Nov 15 '22 06:11

Rafael Sanches


The NSDataDetector class, available in iOS 4.0 and later, is a specialized subclass of NSRegularExpression that has explicit support for detecting phone numbers.

like image 7
Shaggy Frog Avatar answered Nov 15 '22 07:11

Shaggy Frog