The following code should do the following:
- Limit the number of characters that can be entered / inserted in the text field
- Automatically add periods and slashes in appropriate places.
- Prevention of problems by the user by copying / pasting a line that already has the necessary periods / slashes
, ; , .
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *text = textField.text;
if ([text length] == 14 && range.location > 13) {
return NO;
}
text = [text stringByReplacingCharactersInRange:range withString:string];
text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
text = [text stringByReplacingOccurrencesOfString:@"." withString:@""];
text = [text stringByReplacingOccurrencesOfString:@"/" withString:@""];
NSMutableString *mutableText = [text mutableCopy];
for (NSUInteger i = 3; i < mutableText.length && i < 8; i += 4) {
[mutableText insertString:@"." atIndex:i];
}
if (mutableText.length > 11) {
[mutableText insertString:@"/" atIndex:11];
}
text = mutableText;
if (text.length > 14) {
text = [text stringByReplacingCharactersInRange:NSMakeRange(14, mutableText.length-14) withString:@""];
}
textField.text = text;
return NO;
}