8

I have a UITextField with the following restrictions - characters can only be numbers, as in the method below. I want to also limit the number of max characters to 3 digits. How can I modify my method to do that?

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
for (int i = 0; i < [string length]; i++) {
    unichar aCharacter = [string characterAtIndex:i];
    if ([aCharacterSet characterIsMember:aCharacter]) {
        return YES;
    }
}

NSUInteger newLength = self.textField.text.length + string.length - range.length;
return (newLength > 3) ? NO : YES;
}
Adrian P
  • 6,479
  • 4
  • 38
  • 55
  • How is it that some questions get soo many answers? Maybe because none of the answers have been accepted. – Zaxter Sep 14 '14 at 07:08
  • 1
    This may Help and Limit your time for searching answer :) http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield – Basil Mariano May 14 '15 at 07:41
  • This will surely help! 100% accurate http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield – Basil Mariano May 14 '15 at 07:42

6 Answers6

14

o limit the text field use below code.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];    
        return !([newString length] > 3);

}
venki
  • 179
  • 2
  • 10
  • Could you explain what the return statement is doing? – TheM00s3 Jul 08 '14 at 22:07
  • 2
    The method should return true if a planned text substitution should be allowed to happen, false otherwise. The return statement evaluates to true if the new string will be of length 3 or less. – Marius Jeskulke Sep 17 '14 at 06:42
  • It will only allows the user to enter three characters and u can't enter more than 3 characters. – venki Feb 27 '15 at 10:39
4

Your code is close. Try:

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

    NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    for (int i = 0; i < [string length]; i++) {
        unichar aCharacter = [string characterAtIndex:i];
        if (![aCharacterSet characterIsMember:aCharacter]) {
            return NO;
        }
    }

    NSUInteger newLength = self.textField.text.length + string.length - range.length;
    return (newLength > 3) ? NO : YES;
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
2

You can add an observer to UITextFieldTextDidChangeNotification

// add this line in viewDidLoad

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(limitTextField) name:UITextFieldTextDidChangeNotification object:nil];

//dealloc add this 
[[NSNotificationCenter defaultCenter]removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];

//method to limit textfield's characters

-(void)limitTextField
{
   textField.text = [textField.text substringToIndex:3];
}

//or else set delegate of textfield and use this

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([textField.text length]<=3)
   return YES;
else
   return NO;
}

and set the keyBoardType of textfield as UIKeyboardTypeNumberPad to get only numbers. I have not tested or compiled the code, just wrote the logic. Hope it helps :)

Unheilig
  • 16,196
  • 193
  • 68
  • 98
sanjaymathad
  • 232
  • 1
  • 5
2

Setting Maximum Character Limit & Numeric Validation in UITextField

Setting Maximum Character Limit in UITextField:- We can’t directly set the maximum length to the UITextField because it’s class has no max length property, But it can be achieved by using the following text field delegate method.

#define MAX_LENGTH 20

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

NSUInteger newLength = [textField.text length] + [string length] – range.length;

if(newLength > MAX_LENGTH){

     return NO;
   }
   else{
            return YES;
   }
}

Before the text field changes, the UITextField asks the delegate if the specified text should be changed. The text field has not changed at this point, so we grab it’s current length and the string length we’re inserting, minus the range length. If this value is too long (more than 20 characters in this example), return NO to prohibit the change.

> Numeric Validation in UITextField

#define NUMBERS_ONLY 0123456789

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

{
if([textField isEqual:txtPhone])
{
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
    NSString *filteredstring  = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@””];
    return ([string isEqualToString:filteredstring]);
}
   return  TRUE;
}
Community
  • 1
  • 1
Abdul Karim
  • 4,359
  • 1
  • 40
  • 55
0

Try this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *aCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString *filtered =  [[string componentsSeparatedByCharactersInSet:aCharacterSet] componentsJoinedByString:@""];
if ((textField.text.length >2) && (!(string.length == 0)))
            return NO;
        else
            return [string isEqualToString:filtered];
}
user523234
  • 14,323
  • 10
  • 62
  • 102
0

declare this way

 #define MAX_LENGTH_FULLNAME 3

#pragma mark - TextField Delegate method
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if([string length]==0){
        return YES;
    }
    NSUInteger newLength = [textField.text length] + [string length] - range.length;

    if ([string isEqualToString:@"\n"]) {
        [self.txtAnswer resignFirstResponder];
        return NO;
    }
    if (textField == self.txtFName){
        /* for backspace */
        if([string length]==0){
            return YES;
        }
        if (newLength > MAX_LENGTH_FULLNAME) {
            if([string length] > MAX_LENGTH_FULLNAME){
                textField.text = [string substringToIndex:MAX_LENGTH_FULLNAME];
            }
            return NO;
        }
      NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"1234567890"];


        for (int i = 0; i < [string length]; i++) {
            unichar c = [string characterAtIndex:i];
            if ([myCharSet characterIsMember:c]) {
                return YES;
            }
        }
        return NO;

    }
return YES;
}

to allow only numbers you can also just define this way

[textField setKeyboardType:UIKeyboardTypeNumberPad];
Banker Mittal
  • 1,918
  • 14
  • 26