Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 799
sreenivas Avatar asked Feb 28 '12 06:02

sreenivas


1 Answers

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));
}
like image 60
NJones Avatar answered Oct 25 '22 02:10

NJones