How to enter Numbers only in UITextField and limit maximum length?

21,153

Solution 1

Not that I don't like the answer I wrote at this question, that was copy & pasted here also. I'll try to explain your error.

This answer is based on the assumption that your constants are defined something like this:

#define NUMBERS_ONLY @"1234567890"
#define CHARACTER_LIMIT 3

The reason your logic is failing is that you never handle the event when newLength will be equal to the CHARACTER_LIMIT.

To illustrate suppose your textfield is empty and you request to paste the string @"ABC" to the textfield, your delegate method is called. You create the string filtered which correctly evaluates to an empty string, and you can't wait to execute the line return [string isEqualToString:filtered]; but you never actually evaluate that line because you don't meet the entry requirements for the while loop, because newLength is 3. so the simple return (newLength > CHARACTER_LIMIT ) ? NO : YES; decides the return value.

If your CHARACTER_LIMIT is actually 4 for some reason, just imagine @"ABCD" as the string the logic still applies.

Here is a simple example of your function corrected to work. Again I'm assuming that CHARACTER_LIMIT is equal to 3.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}

Solution 2

 -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    // Check for non-numeric characters
    NSUInteger lengthOfString = string.length;
    for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {
        unichar character = [string characterAtIndex:loopIndex];
        if (character < 48) return NO; // 48 unichar for 0
        if (character > 57) return NO; // 57 unichar for 9
    }
    // Check for total length
    NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
    if (proposedNewLength > 3) return NO;
    return YES;
    }

Its working fine for me u can use this code

Solution 3

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *s = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^\\d{0,3}$" options:0 error:nil];
    NSTextCheckingResult *match = [regex firstMatchInString:s options:0 range:NSMakeRange(0, [s length])];
    return (match != nil);
}
Share:
21,153
sreenivas
Author by

sreenivas

Updated on February 28, 2020

Comments

  • sreenivas
    sreenivas about 4 years

    In UITextField we Enter Numeric only and limit up to 3 numeric for this i used below code

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
    
    
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
    
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
    
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    
        while (newLength < CHARACTER_LIMIT) {
            return [string isEqualToString:filtered];
        }
    
    /* Limits the no of characters to be enter in text field */
    
        return (newLength > CHARACTER_LIMIT ) ? NO : YES; 
    
    }
    

    When i press long press on textfield (like below image )and enter string between two numbers it's allowing all special characters and charterers also. enter image description here

  • bluevoid
    bluevoid over 10 years
    could you use [NSCharacterSet decimalDigitCharacterSet] instead?