// Source - https://stackoverflow.com/a/18760472
// Posted by torap, modified by community. See post 'Timeline' for change history
// Retrieved 2025-11-14, License - CC BY-SA 3.0
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField.tag == 8) {
NSCharacterSet *numSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789-"];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
int charCount = [newString length];
if (charCount == 3 || charCount == 7) {
if ([string isEqualToString:@""]){
return YES;
}else{
newString = [newString stringByAppendingString:@"-"];
}
}
if (charCount == 4 || charCount == 8) {
if (![string isEqualToString:@"-"]){
newString = [newString substringToIndex:[newString length]-1];
newString = [newString stringByAppendingString:@"-"];
}
}
if ([newString rangeOfCharacterFromSet:[numSet invertedSet]].location != NSNotFound
|| [string rangeOfString:@"-"].location != NSNotFound
|| charCount > 12) {
return NO;
}
textField.text = newString;
return NO;
}
return YES;}