Allow only alphanumeric characters for a UITextField

WalterF picture WalterF · Sep 24, 2011 · Viewed 31.7k times · Source

How would I go about allowing inputting only alphanumeric characters in an iOS UITextField?

Answer

Noah Witherspoon picture Noah Witherspoon · Sep 24, 2011

Use the UITextFieldDelegate method -textField:shouldChangeCharactersInRange:replacementString: with an NSCharacterSet containing the inverse of the characters you want to allow. For example:

// in -init, -initWithNibName:bundle:, or similar
NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];

- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
    return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}

// in -dealloc
[blockedCharacters release];

Note that you’ll need to declare that your class implements the protocol (i.e. @interface MyClass : SomeSuperclass <UITextFieldDelegate>) and set the text field’s delegate to the instance of your class.