5

I need to determine if a text is an email address, or mobile number, for email address I can use some regular expression, for mobile number I can check if the string has only digits(right?)

and the sequence is like:

is (regex_valid_email(text))
{
    // email
}
else if (all_digits(text))
{
    // mobile number
}

but how do I check if a string has only numbers in iOS?

Thanks

hzxu
  • 5,753
  • 11
  • 60
  • 95
  • 1
    For the second bit. possible duplicate of [How to check if NSString is numeric or not](http://stackoverflow.com/questions/2020360/how-to-check-if-nsstring-is-numeric-or-not) which is itself a dupe of http://stackoverflow.com/questions/1320295/iphone-how-to-check-that-a-string-is-numeric-only - please look next time before asking, we don't really want a million copies of each question :-) – paxdiablo Sep 24 '12 at 02:19
  • For the first bit, it's been well established that the regex capable of doing emails properly is about 27 billion characters in length :-) The best way to check an email is to send something to it with a link that's required to be selected. Not every legal email address is valid. – paxdiablo Sep 24 '12 at 02:22
  • What if the phone number contains dashes? Or parenthesis? – borrrden Sep 24 '12 at 03:07

2 Answers2

10

You create an NSCharacterSet that includes the digits and probably the dash and maybe parentheses (depending on what format you are seeing for the phone numbers). You then invert that set, so you have a set that has everything but those digits and things, then use rangeOfCharactersFromSet and if you get anything but NSNotFound, then you have something other than digits.

rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • I would like to point out that based on the locale, other separators than the dash might be used for phone numbers. For example here in germany we use a slash and/or spaces. – JustSid Sep 24 '12 at 05:03
  • You use the NSCharacterSet method invertedSet – rdelmar Sep 25 '12 at 01:05
  • This check gives YES if string is @"", which in my opinion isn't correct – Foriger Apr 22 '15 at 09:25
5

This should work:

//This is the input string that is either an email or phone number
NSString *input = @"18003234322";

//This is the string that is going to be compared to the input string
NSString *testString = [NSString string];

NSScanner *scanner = [NSScanner scannerWithString:input];

//This is the character set containing all digits. It is used to filter the input string
NSCharacterSet *skips = [NSCharacterSet characterSetWithCharactersInString:@"1234567890"];

//This goes through the input string and puts all the 
//characters that are digits into the new string
[scanner scanCharactersFromSet:skips intoString:&testString];

//If the string containing all the numbers has the same length as the input...
if([input length] == [testString length]) {

    //...then the input contains only numbers and is a phone number, not an email
}
pasawaya
  • 11,515
  • 7
  • 53
  • 92