Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that a input to UITextField is numeric only

How do I validate the string input to a UITextField? I want to check that the string is numeric, including decimal points.

like image 403
g.revolution Avatar asked Aug 24 '09 02:08

g.revolution


People also ask

How do I restrict TextField to numbers only?

Method 1: Changing the Text Field Type from storyboard. Select the text field that you want to restrict to numeric input. Go to its attribute inspector. Select the keyboard type and choose number pad from there.

How do you dismiss a keyboard in Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.


2 Answers

You can do it in a few lines like this:

BOOL valid; NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet]; NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:myInputField.text]; valid = [alphaNums isSupersetOfSet:inStringSet];     if (!valid) // Not numeric 

-- this is for validating input is numeric chars only. Look at the documentation for NSCharacterSet for the other options. You can use characterSetWithCharactersInString to specify any set of valid input characters.

like image 137
Donal O'Danachair Avatar answered Oct 12 '22 15:10

Donal O'Danachair


There are a few ways you could do this:

  1. Use NSNumberFormatter's numberFromString: method. This will return an NSNumber if it can parse the string correctly, or nil if it cannot.
  2. Use NSScanner
  3. Strip any non-numeric character and see if the string still matches
  4. Use a regular expression

IMO, using something like -[NSString doubleValue] wouldn't be the best option because both @"0.0" and @"abc" will have a doubleValue of 0. The *value methods all return 0 if they're not able to convert the string properly, so it would be difficult to distinguish between a legitimate string of @"0" and a non-valid string. Something like C's strtol function would have the same issue.

I think using NSNumberFormatter would be the best option, since it takes locale into account (ie, the number @"1,23" in Europe, versus @"1.23" in the USA).

like image 42
Dave DeLong Avatar answered Oct 12 '22 14:10

Dave DeLong