Check that a input to UITextField is numeric only

g.revolution picture g.revolution · Aug 24, 2009 · Viewed 104.3k times · Source

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

Answer

Donal O'Danachair picture Donal O'Danachair · Oct 1, 2010

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.