Take the 2-minute tour ×

Now I am trying to add a front end check on my app to detect if user input only number in the textfield.

I use:

- (IBAction)checkID:(UITextField *)sender {
if ([sender.text isEqualToString:@""]) {
    sender.text = @"This information is required";
    sender.backgroundColor =[UIColor redColor];
}else if (![sender.text intValue]) {
    sender.text = [sender.text stringByAppendingString:@" is not valid number"];
    sender.backgroundColor =[UIColor redColor];
NSLog(@"send.text is %@, intValue is %d",sender.text,[sender.text intValue]);


But I found it text begins with number and ends with string, its intValue is still the number. In my text, text is "00001aa", but the intValue is 1.

Is there any other way to filter out this "00001aa" text?

Thanks in advance.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Yes, you can use NSRegularExpression, or NSCharacterSet (works for positive numbers).

For regular expressions, use ^[-+]?[0-9]+$.

NSRegularExpression *numEx = [NSRegularExpression
    regularExpressionWithPattern:@"^[-+]?[0-9]+$" options:0 error:nil
NSLog(@"%ld", [numEx numberOfMatchesInString:@"-200" options:0 range:NSMakeRange(0, 4)]);
NSLog(@"%ld", [numEx numberOfMatchesInString:@"001A" options:0 range:NSMakeRange(0, 4)]);

For character set, use [NSCharacterSet decimalDigitCharacterSet].

BOOL isNum = [[NSCharacterSet decimalDigitCharacterSet]
    isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:@"001AA"]
share|improve this answer
Thanks, I will use this solution –  Kenny Sep 4 '12 at 4:43

Your Answer


