Iphone UITextField only integer

35,474

Solution 1

http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Objective-C

Or you could ensure that only the numeric keyboard appears when the focus comes on the field

Solution 2

Implementing shouldChangeCharactersInRange method as below does not allow the user input non-numeric characters.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0) || [string isEqualToString:@""];
}

This returns YES if the string is numeric, NO otherwise. the [string isEqualToString@""] is to support the backspace key to delete.

I love this approach because it's clean.

Solution 3

Be sure to set your text field delegate

Use the following function to ensure user can type in numbers only:

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

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

    NSNumber* candidateNumber;

    NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    range = NSMakeRange(0, [candidateString length]);

    [numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];

    if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length])) {

        return NO;
    }
    else 
    {
        return YES;
    }
}

Solution 4

Try this: It will stop user to enter any character other then numbers

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

   if ([string rangeOfCharacterFromSet:nonNumberSet].location != NSNotFound) 
   {
       return NO;
   }
   return YES;
}

Solution 5

To only allow for numeric input:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    return [string isEqualToString:@""] || 
        ([string stringByTrimmingCharactersInSet:
            [[NSCharacterSet decimalDigitCharacterSet] invertedSet]].length > 0);
}

To test for an integer:

- (BOOL)isNumeric:(NSString *)input {
    for (int i = 0; i < [input length]; i++) {
        char c = [input characterAtIndex:i];
        // Allow a leading '-' for negative integers
        if (!((c == '-' && i == 0) || (c >= '0' && c <= '9'))) {
            return NO;
        }
    }
    return YES;
}
Share:
35,474
Raphael Pinto
Author by

Raphael Pinto

Updated on August 26, 2020

Comments

  • Raphael Pinto
    Raphael Pinto over 3 years

    I have a UITextField in my IB and I want to check out if the user entered only numbers (no char)and get the integer value.

    I get the integer value of the UITextField like that :

    int integer = [myUITexrtField.text intValue];
    

    When I put a character ( , ; . ) it return me 0 and I don't know how to detect that it is not only numbers.

    How can I do?

  • GarethPrice
    GarethPrice over 12 years
    This does not work if the first character typed is a letter. If a number is typed first, then a letter is typed it works, however.
  • Shoerob
    Shoerob over 12 years
    Relying on the numeric keyboard isn't safe since the user could potentially paste string data into the field instead of even using the keyboard.
  • andershqst
    andershqst over 12 years
    To enable delete: return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0) || [string isEqualToString:@""];
  • endo.anaconda
    endo.anaconda about 12 years
    last answer is more accourate
  • mbogh
    mbogh almost 12 years
    Only problem is if a user paste in a string e.g. 1n1a, stringByTrimmingCharactersInSet: will only remove from start and end of the string. Do something like: NSRegularExpression *numbersOnly = [NSRegularExpression regularExpressionWithPattern:@"[0-9]+" options:NSRegularExpressionCaseInsensitive error:&error]; NSInteger numberOfMatches = [numbersOnly numberOfMatchesInString:string options:0 range:NSMakeRange(0, string.length)]; if (numberOfMatches != 1 && string.length != 0) { shouldChange = NO; }
  • mah
    mah over 11 years
    An answer was provided and accepted 2 years ago. Please do not answer such old questions which have already been answered unless you have something substantive to add.
  • Yaroslav
    Yaroslav over 11 years
    What does your answer adds to the previous ones? Why it is valuable and you think should be an answer? There are already several high upvoted answers to this question, why your is different?
  • Christian Loncle
    Christian Loncle over 11 years
    this was a very quick solution to implement. don't forget to add the textField delegate to the .h file
  • septerr
    septerr over 10 years
    @mbogh 's comment should be the answer.
  • Jason
    Jason about 9 years
    Alternatively, you could change the second line to return [string stringByTrimmingCharactersInSet:numbers].length == string.length;