views:

140

answers:

4

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

+3  A: 

In iOS 4.0+ there are built in classes to do this, NSRegularExpression

In everything else you can either use a 3rd party RegEx library, or use an NSPredicate if your needs are narrow enough

Joshua Weinberg
+2  A: 

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).

Dave DeLong
Just had to one-up me, didn't you :)
Joshua Weinberg
That only works in the US.
Yuji
It doesn't even work across the whole US, so I'd assume the OP has a precisely narrow use case he's dealing with.
quixoto
Yes, it's a specific narrow use case I am looking for.
ohho
What is the meaning of the '?' (last char of phoneRegex)?
ohho
It means "none or one" of the last group. Conceptually, you'd probably think of the optional digits as coming at the beginning for a 10- vs 7-digit phone number, but since you have a requirement on the first digit, it's easiest to call the last three digits the optional ones.
Seamus Campbell
+3  A: 

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.

Yuji
+1  A: 

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

Shaggy Frog