Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField limit the number and type of characters

I have two text fields that I would like to limit the number and type of characters. I have used the following bits of code to do each function separately but cannot find a way to do both within the same function.

To restrict the type of character:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // Only characters in the NSCharacterSet you choose will insertable.
    NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefgABCDEFG"] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
    return [string isEqualToString:filtered];
}

and to limit the number of characters:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
 if (textField.text.length >= 10 && range.length == 0)
 return NO;
return YES;
}
like image 541
Tool Avatar asked Sep 04 '12 14:09

Tool


1 Answers

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.text.length >= 10 && range.length == 0)
       return NO;
    // Only characters in the NSCharacterSet you choose will insertable.
    NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefgABCDEFG"] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
    return [string isEqualToString:filtered];
}

Edited

If you want to add different condition for third text field then you can do like this.
Create the reference for 3rd text fild say thirdField

then use this

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == thirdField) {
        //your contion e.g
        if (textField.text.length < 7) {
            return YES;
        } else {
            return NO;
        }        
    }
    else {
        if (textField.text.length >= 10 && range.length == 0)
            return NO;
        // Only characters in the NSCharacterSet you choose will insertable.
        NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefgABCDEFG"] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
}
like image 138
Inder Kumar Rathore Avatar answered Sep 17 '22 13:09

Inder Kumar Rathore