How do I validate the string input to a UITextField
? I want to check that the string is numeric, including decimal points.
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.
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.
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.
There are a few ways you could do this:
nil
if it cannot.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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With