I want display "1 (xxx)-(xxx)-(xxx)" in a UITextfield
and only enter 10 digits.
- It's valid 1 to 9 numbers.
- It's starting only 1.
- If you enter 0 it's not taken.
How do I achieve this?
I have done Us Phone Number validation in one of my projects. Hope this helps you.
-(void)textFieldDidBeginEditing:(UITextField *)textField {
[textField performSelector:@selector(shouldChangeTextInRange:replacementText:)];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *text = textField.text;
NSString *acceptedcharacters = @"0123456789-/";
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptedcharacters] invertedSet];
const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
int isBackSpace = strcmp(_char, "\b");
if (isBackSpace == -8) {
NSLog(@"deleted");
}
else {
if (textField.text.length == 1) {
textField.text = [NSString stringWithFormat:@"%@-",text];
return YES;
}
if (textField.text.length == 5) {
textField.text = [NSString stringWithFormat:@"%@-",text];
return YES;
}
if (textField.text.length == 9) {
textField.text = [NSString stringWithFormat:@"%@-",text];
return YES;
}
}
// if (textField == self.phoneNumber_txtField) {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 14) ? NO : YES;
// }
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}