NSCharacterSet: How do I add "_" to alphanumericCharacterSet text restriction?

typeoneerror picture typeoneerror · May 4, 2010 · Viewed 25.3k times · Source

Building an NSCharacter set to restrict a UITextField for entering user names. I want the user to be able to also enter an underscore (so [A-Za-z0-9_]) but alphanumericCharacterSet does not include it. Is there a way to specify a range like that in short form? I see + (id)characterSetWithRange:(NSRange)aRange, but I'm not really understanding how that would work.

I've got a simple UITextField sub-class that I pass the character set to. The restriction works fine and doesn't allow the user to enter anything but alpha numeric. Just need to add the "_" to those allowances.

NSCharacterSet *characterSet = [NSCharacterSet alphanumericCharacterSet];
[textField setAllowed:characterSet];
[textField setFrame:frame];

Answer

drawnonward picture drawnonward · May 4, 2010

Objective-C

NSMutableCharacterSet *_alnum = [NSMutableCharacterSet characterSetWithCharactersInString:@"_"];
[_alnum formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];

Swift

let _alnum = NSMutableCharacterSet(charactersIn: "_")
_alnum.formUnion(with: .alphanumerics)