I have a TextField and wanted to know if the user just pressed numbers
eg:: _tfNumber.text only has numbers?
is there any function on NSString for this?
I have a TextField and wanted to know if the user just pressed numbers
eg:: _tfNumber.text only has numbers?
is there any function on NSString for this?
try this:
NSCharacterSet *_NumericOnly = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *myStringSet = [NSCharacterSet characterSetWithCharactersInString:mystring];
if ([_NumericOnly isSupersetOfSet: myStringSet]) {
NSLog(@"String has only numbers");
}
I got it from: http://i-software-developers.com/2013/07/01/check-if-nsstring-contains-only-numbers/
You can use this method in your UITextField
's delegate method textField:shouldChangeCharactersInRange:replacementString:
and do the verification while the user is typing.
This will let you know if all of the characters are numbers:
NSString *originalString = @"1234";
NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
NSString * trimmedString = [originalString stringByTrimmingCharactersInSet:numberSet];
if ((trimmedString.length == 0) && (originalString.length > 0)) {
NSLog(@"Original string was all numbers.");
}
Note that this ensures it won't give a false positive for the empty string, which technically also doesn't contain any non-numbers.
No, but it should be easy to write:
- (BOOL)justContainsNumbers:(NSString *)str {
if ([str length] == 0)
return NO;
for (NSUInteger i = 0; i < [str length]; i++)
if (!isdigit([str characterAtIndex:i]))
return NO;
return YES;
}
Let's try regular Expression,
NSString * numberReg = @"[0-9]";
NSPredicate * numberCheck = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberReg];
if ([numberCheck evaluateWithObject:textField.text])
NSLog (@"Number");
No. NSString
is not an NSNumber
and any values you get from a UITextField
will be an NSString
. See THIS SO answer for converting that entered NSString
value into an NSNumber
.