Skip to content

Instantly share code, notes, and snippets.

@gdavis
Created May 31, 2012 19:46
Show Gist options
  • Save gdavis/2845766 to your computer and use it in GitHub Desktop.
Save gdavis/2845766 to your computer and use it in GitHub Desktop.
iOS Phone Number Field Formatting With User Entry
#pragma mark - Phone Number Field Formatting
// Adopted from: http://stackoverflow.com/questions/6052966/phone-number-formatting
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.mobileNumberField || textField == self.homeNumberField || textField == self.workNumberField) {
int length = [self getLength:textField.text];
if(length == 10) {
if(range.length == 0)
return NO;
}
if(length == 3) {
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:@"(%@) ",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"%@",[num substringToIndex:3]];
}
else if(length == 6) {
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:@"(%@) %@-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]];
}
}
return YES;
}
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
int length = [mobileNumber length];
if(length > 10) {
mobileNumber = [mobileNumber substringFromIndex: length-10];
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
int length = [mobileNumber length];
return length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment