I am trying to validate 10 digit phone number entered in a UITextfield. Actually I need the number in the format xxx-xxx-xxxx. So I would not want the user to delete - symbol.
I tried using various approaches mentioned here: Detect backspace in UITextField, but none of them seems to work.
My current approach is:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (range.location == 12) {
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Invalid Input" message:@"Phone number can contain only 10 digits." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[testTextField resignFirstResponder];
return NO;
}
if (range.length == 0 && [blockedCharacters characterIsMember:[string characterAtIndex:0]]) {
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Invalid Input" message:@"Please enter only numbers.\nTry again." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
return NO;
}
if (range.length == 0 &&
(range.location == 3 || range.location == 7)) {
textField.text = [NSString stringWithFormat:@"%@-%@", textField.text, string];
return NO;
}
if (range.length == 1 &&
(range.location == 4 || range.location == 8)) {
range.location--;
range.length = 2;
textField.text = [textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
return YES;
}
Any thoughts on this?
Thank you very much.