Reputation: 988
I am trying to validate textfield for numbers only.
I am using the following method:
if(isnumber(noOfPassengers.text.intValue))
{
NSLog(@"value entered correctly.");
return ;
}
else
NSLog(@"Error: Only numerica values are accepted");
isnumber() function is not working as expected. I would like to validate for numbers only. Got stuck here. Any other inbuilt function to check for numbers or even characters?
Upvotes: 1
Views: 6601
Reputation: 3813
Simple answer to your question is just show Numeric keyboard and check the value then. You don't have to implement UITextFieldDelegate's @Ben.s suggested.
Upvotes: -2
Reputation: 48396
You haven't posted any code for your function isnumber
, so it's impossible to diagnose the problem there. However, writing the function from scratch, here is what I would do:
-(BOOL)isNumeric:(NSString*)inputString{
NSCharacterSet *alphaNumbersSet = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *stringSet = [NSCharacterSet characterSetWithCharactersInString:inputString];
return [alphaNumbersSet isSupersetOfSet:stringSet];
}
Upvotes: 4
Reputation: 4920
Use NSScanner:
int iValue;
if (noOfPassengers.text.length > 0 && [[NSScanner scannerWithString:noOfPassengers.text] scanInt:&iValue]) {
//do smomething with iValue (int value from noOfPassengers.text)
NSLog(@"value entered correctly.");
return ;
}
else
NSLog(@"Error: Only numerica values are accepted");
Upvotes: 1
Reputation: 69402
The correct thing to do here is to implement the UITextFieldDelegate
's textField:shouldChangeCharactersInRange:replacementString:
to only accept numeric characters.
In the delegate method, return YES
and strip any characters that aren't in the decimal character set.
Upvotes: 3
Reputation: 8109
for iOS, you should allow only numeric keyboard to appear instead. user will have no choice to input any other value except numbers..
Upvotes: -2