views:

163

answers:

1

Hi,

How can I check if a user enters a number in my UITextField. Basically its a mark im accepting between 0-100 and it can be a decimal....I heard i can try to convert it to a NSNumber type and see if it returns null.

Not suree Any help would be appreciated.

I have tried if(grade.text doubleValue] == 0){ //Not a number }

but then it still can accept "23f".

Thanks

A: 

Use NSScanner to detect whether a valid integer is in the string.

NSScanner * scanner = [NSScanner scannerWithString:myTextField.text];
NSInteger * integer;
if([scanner scanInteger:&integer]) {
  // valid number found
} else {
  // cry about it
}

You can improve on this by validating the text in the UITextField delegate method textField:shouldChangeCharactersInRange:replacementString: to prevent the user from even entering an invalid value.

codewarrior
Using `scanDouble:` would have the same side-effect as `doubleValue` of allowing the 'f' character, since it indicates floating-point values in C. What you can do instead is use the delegate method to prevent the user from entering the 'f'.
codewarrior
the Delegate Method does not seem to work, I have connected the controls Delegate
Jimmy
"does not seem to work" is too vague, we'll need more details.
codewarrior
`scanDouble:` is not "allowing" the 'f' character, it's just stopping the scan when it hits it. To verify that the field contains only the number, with no trailing garbage, you need to test `[scanner isAtEnd]` after `scanDouble:` returns successfully.
David Gelhar
Also, think about using a numeric keyboard: `textField.keyboardType = UIKeyboardTypeNumberPad`
0xced