1

I have to validate a phone number which is in following format

(974) 041-0475

I have tried with regex @"^+(?:[0-9] ?){6,14}[0-9]$" but its not working for above example. It's working for plain digits.

Tariq
  • 9,861
  • 12
  • 62
  • 103

2 Answers2

1
You can use any of the regex according to your requirement
\(\d+\)\s*?\d+\-\d+
      OR
\(\d{3}\)\s*?\d{3}\-\d{4}   
0
US Phone Number Validation
NSString *unformatted = textField.text;//pass textfield object with text property
    NSArray *stringComponents = [NSArray arrayWithObjects:[unformatted substringWithRange:NSMakeRange(0, 3)],
                                 [unformatted substringWithRange:NSMakeRange(3, 3)],
                                 [unformatted substringWithRange:NSMakeRange(6, [unformatted length]-6)], nil];

    NSString *formattedString = [NSString stringWithFormat:@"(%@)%@-%@",
    [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1],
    [stringComponents objectAtIndex:2]];NSLog(@"Formatted Phone Number: %@", formattedString);

- (BOOL) validatePhoneWithString:(NSString *)phone
{
    NSString *str = @"(([+]{1}|[0]{2}){0,1}+[1]{1}){0,1}+[ ]{0,1}+(?:[-( ]{0,1}[0-9]{3}[-) ]{0,1}){0,1}+[ ]{0,1}+[0-9]{2,3}+[0-9- ]{4,8}";
    NSPredicate *no = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",str];
    return [no evaluateWithObject:phone];
}
Mike
  • 737
  • 1
  • 6
  • 14
  • 1
    This seems to be copy-pasted from http://stackoverflow.com/a/7527645/ and http://stackoverflow.com/a/7954218/ Please credit your sources when you use them verbatim. – jscs May 29 '13 at 07:58