Heena
Heena

Reputation: 2358

Regular expression for US phone number not working

This type of questions are asked so many times on SO but i am having problem with expression and its not working for me.

I need to allow only numbers,(,),- in phone number and for that i have code as follows. But only uncommented expression is working and that is for only numbers no (,),- are allowed and i searched and got other expressions which should allow (,),- but those are not working too.

What could be wrong? Example: 9876545678, (123) 123-7657

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        if ([string isEqualToString:@""]) {
            return TRUE;
        }
        if(textField == aTfdPhone)
        {
            if ([string isEqualToString:@"."]) {
                    return NO;
                 }
             NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

             NSString *expression = @"^([0-9]+)?(\\.([0-9])?)?$";
    //       NSString *expression = @"^[(]?[2-9][0-9]{2}[)]?[ -]?[0-9]{3}[ -]?[0-9]{4}$";
       //      NSString * const expression = @"^([+-]{1})([0-9]{3})$";
             NSError *error = nil;

             NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression 
                                                         options:NSRegularExpressionCaseInsensitive 
                                                         error:&error];
            if (error) {
                NSLog(@"error %@", error);
            }
            NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
                                                       options:0
                                                    range:NSMakeRange(0, [newString length])];
            if (numberOfMatches == 0){
                    return NO;
             }
        }
        return TRUE; 
    }

Upvotes: 0

Views: 1485

Answers (1)

Dima Chubarov
Dima Chubarov

Reputation: 17159

Your second attempt fails to recognize (123) 123-7657 because of the first digit:

It should be

   NSString *expression = @"^[(]?[1-9][0-9]{2}[)]?[ -]?[0-9]{3}[ -]?[0-9]{4}$";

not

   NSString *expression = @"^[(]?[2-9][0-9]{2}[)]?[ -]?[0-9]{3}[ -]?[0-9]{4}$";

The only difference is the operator matching the first digit [2-9] would not match 1.

Upvotes: 1

Related Questions