2013-10-01 32 views
0

我必须输入字符串格式化为电话number.For我使用如何验证和格式的输入字符串1234567890至123-456-7890

(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)); 
} 

这里

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

,但它不是编辑回来。

请给一些想法

+0

我不知道,你可以放心地忽略range.position,你做的方式。 –

+1

更好的方法来实现相同的, 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 – satheeshwaran

+0

请参阅我的答案在http://stackoverflow.com/questions/1246439/uitextfield-for-phone-number/35378246#35378246 – iphaaw

回答

0

您正在使用的方法是确定是否允许改变该文本字段的UITextFieldDelegate方法 - 定的范围和替换文本,应在变化作出(YES或没有)。

您正尝试在键入字符串时对它进行格式化 - 为此,您还需要更新textField.text属性的值。这可以用相同的方法完成,然后返回“否”。

0

进行验证,

- (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]; 
} 

你可以使用这个格式化字符串,

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]];