Configuring the phone number format by typing


I am setting phone number format such as (222) 233-3441 while typing in textField. When user keeps entering more that 14 characters (including special characters), all special characters will be removed and numbers alone be displayed (i.e. 222233344188). And when they reach back to 14 characters on deleting some characters, the phone number format will be set again. I achieved as i wanted. But facing problem while deleting.

  • While deleting - format is being applied when number of character reach to 10. So 2222333441 becomes (222) 233-3441.
  • Keep deleting, getting looped since format getting applied and the character reach to 10 again.

Became blank to move forward. Please push me up with your valuable suggestions to resolve this issue.

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if(string.length!=0){   //detect backspace

        if (textField.text.length == 0)
            textField.text = [NSString stringWithFormat:@"(%@",textField.text];

        if (textField.text.length == 4)
            textField.text = [NSString stringWithFormat:@"%@) ",textField.text];

        if (textField.text.length == 9)
            textField.text = [NSString stringWithFormat:@"%@-",textField.text];

        if (textField.text.length>13){

            NSString *value=[NSString stringWithString:textField.text];
            textField.text=[[value componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]componentsJoinedByString:@""];



            NSMutableString *text=[NSMutableString stringWithString:textField.text];
            [text insertString:@"(" atIndex:0];
            [text insertString:@") " atIndex:4];
            [text insertString:@"-" atIndex:9];


     return YES;


I agree with the comments, i.e. this is not advisable design.

Still, the programming question is interesting. My approach would be to first "normalize" the text, i.e. remove all non-numeric characters and then apply your logic.

textField.text=[[textField.text componentsSeparatedByCharactersInSet:
     [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]