0

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.

Community
  • 1
  • 1
Pulkit Verma
  • 80
  • 1
  • 8
  • possible duplicate of [Detect backspace in UITextField](http://stackoverflow.com/questions/1977934/detect-backspace-in-uitextfield) – Sulthan Feb 20 '13 at 13:34
  • Voted to close because the solution in the mentioned question does work. However, you don't actually want to implement backspace, you just want to check the contents of the text field. – Sulthan Feb 20 '13 at 13:34
  • 3
    Why don't you let the user to input the number as he wants, and then you modify it after edit ends applying your format? – apascual Feb 20 '13 at 13:40
  • I do have to ask: What does "but none of them seems to work" mean? The last section of your code looks reasonable. What is the problem that you are seeing? – lnafziger Feb 20 '13 at 15:44
  • Yeah the workaround suggested by apascua seems to work for me. – Pulkit Verma Feb 22 '13 at 08:59

4 Answers4

4

Subclass UITextField class and override - (void)deleteBackward then you will get message of every backspace press on keyboard. And don't forget call super at the beginning of the function.

Example:

- (void)deleteBackward
{
    [super deleteBackward];
    [self.delegate deleteTapped:self];

}
Mysiaq
  • 555
  • 4
  • 13
1

I faced a similar problem like this:

I know you need to the - inside the numbers to be like xxx-xxx-xxxx.

This is how i tackled it:

-(void)textFieldDidEndEditing:(UITextField *)textField{
     if (self.tf == textField) {
        NSMutableString *stringtf = [NSMutableString stringWithString:self.tf.text];
        [stringtf insertString:@"-" atIndex:2];
        [stringtf insertString:@"-" atIndex:5];
        tf.text = stringDID;
    }
}

So once the user is done editing the number, then I add the - for them.

lakshmen
  • 28,346
  • 66
  • 178
  • 276
  • Its exactly what [apascua](http://stackoverflow.com/users/2046951/apascua) was talking about. Thanks a lot. But my original question is still unanswered. Is there any way by which I can stop user from deleting the - symbol? – Pulkit Verma Feb 22 '13 at 09:12
1

Give this a try. What I'm basically doing here is checking for an empty key click which indicates a backspace. We then check the last two characters to see if it contains a '-' if so we remove both. Then return NO because we are handling the backspace ourself. I haven't actually run the code but should work in theory. This means a number like '123-456-7' will end up like '123-456'. You can adjust the logic to suit your needs. Cheers.

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if([string isEqualToString:@""] && [textField.text length] > 3)
    {
        NSString *lastChars = [textField.text substringFromIndex:[textField.text length] - 2];

        if([lastChars rangeOfString:@"-"].location != NSNotFound)
        {
            NSString *newString = [textField.text substringToIndex:[textField.text length] - 2];
            [textField setText:newString];

            return NO;
        }
    }

    return YES;
}
Vinh Nguyen
  • 401
  • 4
  • 3
0

This code may provide some clue :

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     

if (textField.tag==txtYourTextField.tag) {

    const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
    int isBackSpace = strcmp(_char, "\b");

    if (isBackSpace == -8) {
        NSLog(@"isBackSpace");
        return YES; // is backspace
    }
    else if (textField.text.length == 10) {
        return YES;
    }
}

return NO; }
Jayprakash Dubey
  • 35,723
  • 18
  • 170
  • 177