user1140780
user1140780

Reputation: 988

Validation for numbers (0-9) in textfield

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

Answers (5)

AAV
AAV

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

PengOne
PengOne

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

Tomasz Wojtkowiak
Tomasz Wojtkowiak

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

Ben S
Ben S

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

Saurabh Passolia
Saurabh Passolia

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

Related Questions