2013-10-01 33 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]];