iPhone code snippet: Phone number formatter

If you have had to create a text field for a user to enter a phone number, you may have had to do this yourself.

If not, this snippet may save you 15 minutes. Set the keyboard type to phone pad and add these 2 methods to the delegate of your text field. This code does rely on a UITextField category method: fullRange. You can implement this yourself, it just returns an NSRange representing the entire string.

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

    NSMutableString *localText;

    if(range.length>0){

        localText = [[textField text] mutableCopy];

        NSRange deletionRange = [localText fullRange];
        deletionRange.location = ([localText length]-1);
        deletionRange.length = 1;
        [localText deleteCharactersInRange:deletionRange];

        phoneNumber.text = localText;
        [localText release];

    } else if([[textField text] length]<13){

        if([[textField text] length]>0){

            localText = [[textField text] mutableCopy];

            [localText replaceOccurrencesOfString:openParentheses withString:@"" options:NSCaseInsensitiveSearch range:[localText fullRange]];
            [localText replaceOccurrencesOfString:closeParentheses withString:@"" options:NSCaseInsensitiveSearch range:[localText fullRange]];
            [localText replaceOccurrencesOfString:dash withString:@"" options:NSCaseInsensitiveSearch range:[localText fullRange]];

            [localText appendString:string];
            self.phoneNumberString = [[localText copy] autorelease];

            [localText insertString:openParentheses atIndex:0];

            if([localText length]>3)
                [localText insertString:closeParentheses atIndex:4];

            if([localText length]>7)
                [localText insertString:dash atIndex:8];

        } else{

            localText = [openParentheses mutableCopy];
            [localText appendString:string];

        }

        phoneNumber.text = localText;
        [localText release];

    }

    return NO;

}

- (BOOL)textFieldShouldClear:(UITextField *)textField{

    phoneNumber.text = @"";
    return NO;
}

Tags: ,

One Response to “iPhone code snippet: Phone number formatter”

  1. Omar Says:

    This works like a champ.

    So to complete the help for someone who is newbie:

    Where you see:
    [localText fullRange]
    i.e the use of “fullRange”,
    Just replace that with:
    NSMakeRange(0,[cname length])
    Assuming cname is delcared like this below:
    NSMutableString *cname = [NSMutableString stringWithString:str];

    Hope that additional info make save you an additional 1 minute :-)

Leave a Reply