iOS : Validate textfield and detect backspace is pressed

 There is beatifull method in UITextFieldDelegate  -

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

Parameters
textFiled = The text field containing the text.
range = range of characters to be replaced.
string = replacement string

Detect backspace :

The parameter range is NSRange object- NSRange is a structure used to describe a portion of a series - such as characters in a string or objects in an NSArray object.  So this can be used to detect what key is pressed based on the length of the range.

eg: if(range.length == 1){
 //Then its a backspace.
}

if you want to restrict users from typing in more than few characters then you can use the range.length and range.location


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

{
    //this check whether the backspace key is pressed
    if (range.length == 1) {
        return YES;
    }
   
    if(range.location + range.length > 7 ||
       [textField.text length] + [string length] > 8) {
        return NO;
    } else {
        return YES;
    }
}



No comments: