views:

3725

answers:

7

My application allows the user to enter a numeric value (currency) in a UITextField control, but the keyboard layout that I wish was available is unfortunately not one of the built-in options, so I had to choose the "Numbers & Punctuation" option in Interface Builder. Here's the corresponding dialog window in IB:

So when my application asks the user for the input, it is displaying the following:

Which is perfectly fine, but look at all of the extra keys available to the user! One could easily enter "12;56!" in the text field, and I assume I have to validate that somehow.

So my question is: how do I validate currency values entered into a UITextField?

+3  A: 

Perhaps you could attach a UITextFieldDelegate on the control and have it implement textField:shouldChangeCharactersInRange:replacementString: That way, if it sees any characters that you don't want in the field, it can reject them.

Marc Novakowski
+2  A: 

In conjunction with the textField:shouldChangeCharactersInRange:replacementString: suggestion made by Marc, you should pass the text through an NSNumberFormatter using an NSNumberFormatterCurrencyStyle. This will handle the quirks of currency formatting and handle locale specific options.

There's a "Data Formatting Programming Guide for Cocoa" section in the iPhone documentation if you search for it. Sadly, most of the UI information here is Mac OS X specific (doesnt work on iPhone) but it'll show you how to use the formatter classes.

Matt Gallagher
+1  A: 

Using an NSNumberFormatter is the correct answer. It will handle validation and converting the string to and from the correct object type.

Marc Charbonneau
+5  A: 
what about negative numbers? wouldn't you want to add "-" to the valid set that you invert?
Erich Mirabal
+1  A: 

If you want them to only be able to enter numbers - you might also consider the number keypad

Grouchal
A: 

Using shouldChangeCharactersInRange screws up the pop-up key board as the backspace button doesn't work.

Number formatter is the way to go. Here's a sample I used to find positive decimals. I call it during the validation check- for e.g. when the user clicks on the save button.

    -(BOOL) isPositiveNumber: (NSString *) numberString {

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

    NSNumber *aNumber  =  [numberFormatter numberFromString:numberString];
    [numberFormatter release];

    if ([aNumber floatValue] > 0) {
        NSLog( @"Found positive number %4.2f",[aNumber floatValue] );

        return YES;
    }
    else {
        return NO;
    }
}
Gamma-Point
A: 

You can also use Gamma-Point solution and evaluate if *aNumber is Nil, if its Nil, then it means a character that wasnt 0-9 . or , was entered, this way you can validate just numbers, it will nil the variable if any no-number char is entered.

Aku