0

I have to format input string as phone number.For i am using

(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

   if (string.length==3||string.length==7) {
    filtered =[filtered  stringByAppendingString:@"-"];
}
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}

here

  #define NUMBERS_ONLY @"1234567890-"
  #define CHARACTER_LIMIT 12

but its not editing back.

Please give some ideas

  • I'm not sure you can safely ignore range.position the way that you do. – Hot Licks Oct 01 '13 at 11:37
  • 1
    Better ways to implement the same, http://stackoverflow.com/questions/7184094/how-to-use-phonenumberformatter-class-to-format-phone-number-in-uitextfield http://stackoverflow.com/questions/1246439/uitextfield-for-phone-number – Satheesh Oct 01 '13 at 12:17
  • Please see my answer at http://stackoverflow.com/questions/1246439/uitextfield-for-phone-number/35378246#35378246 – iphaaw Feb 13 '16 at 09:34

2 Answers2

0

The method you're using is a UITextFieldDelegate method that determines whether or not to allow a change to the text field - given the range and replacement text, should the change be made (YES or NO).

You're trying to format a string while it is being typed - for this you'll also need to update the value of the textField.text property. This could be done in the same method while returning a "NO" afterwards.

Stavash
  • 14,244
  • 5
  • 52
  • 80
0

For validation,

- (BOOL) isValidPhoneNumber
{
    NSString *numberRegex = @"(([+]{1}|[0]{2}){0,1}+[0]{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 *numberTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",numberRegex];
    return [numberTest evaluateWithObject:self.inputString];
}

You can use this for formatting the string,

  self.inputString = @"1234567890"   
NSArray *stringComponents = [NSArray arrayWithObjects:[self.inputString substringWithRange:NSMakeRange(0, 3)],
                                         [self.inputString substringWithRange:NSMakeRange(3, 3)],
                                         [self.inputString substringWithRange:NSMakeRange(6, [self.inputString length]-6)], nil];

            NSString *formattedString = [NSString stringWithFormat:@"%@-%@-%@", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];
karthika
  • 4,085
  • 3
  • 21
  • 23