Pulkit Verma
Pulkit Verma

Reputation: 80

Detect backspace press in iOS

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.

Upvotes: 0

Views: 2629

Answers (4)

Vinh Nguyen
Vinh Nguyen

Reputation: 401

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;
}

Upvotes: 1

Jayprakash Dubey
Jayprakash Dubey

Reputation: 36447

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; }

Upvotes: 0

Mysiaq
Mysiaq

Reputation: 555

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];

}

Upvotes: 4

lakshmen
lakshmen

Reputation: 29064

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.

Upvotes: 1

Related Questions