How to verify input in UITextField (i.e., numeric input) How to verify input in UITextField (i.e., numeric input) objective-c objective-c

How to verify input in UITextField (i.e., numeric input)


I had a similar requirement and the solution ultimately turned out to be fairly trivial. Unfortunately a lot of the questions and answers related to this question are about validating or formatting numeric values, not controlling what a user could input.

The following implementation of the shouldChangeCharactersInRange delegate method is my solution. As always, RegularExpressions rock in this situation. RegExLib.com is an excellent source for useful RegEx's. I'm not a RegEx guru and always struggle a bit putting them together so any suggestions to improve it are welcome.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{    if (textField == self.quantityTextField)    {        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];        NSString *expression = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$";        NSError *error = nil;        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression                                                                                options:NSRegularExpressionCaseInsensitive                                                                                  error:&error];        NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString                                                            options:0                                                              range:NSMakeRange(0, [newString length])];                if (numberOfMatches == 0)            return NO;            }    return YES;}

The above code allows the user to input these kinds of values: 1, 1.1, 1.11, .1, .11


The question that Dave DeLong was trying to post is 1320295 and looks very relevant.This appears to be an old question, youve probably found your solution, Would be nice if you share it will all =)


You can cast the content of your textfield in float and format it by using the code below :

float myFloat = [myTextField floatValue];NSString *formatString = [NSString stringWithFormat:@"%%1.%if", 2]; //2 decimals after pointNSString *resultString = [NSString stringWithFormat:formatString, myFloat];

If you want to allow only numeric values in your textfield, you can just reput the resultString in your textField so any not allowed text will be replaced by the formatted float value.

If the user puts "abc12.4" the result will be "0". So it would be better if you use the UITextFieldDelegate method :

textField:shouldChangeCharactersInRange:replacementString:

to check the last key tapped by user. You can just compare it to know if it's a numeric value or a point/comma.