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

IphoneObjective CNscharacterset

Iphone Problem Overview


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];

Iphone Solutions


Solution 1 - Iphone

Objective-C

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

Swift

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

Solution 2 - Iphone

Another way would have been to make it mutable and add it.

Objective-C

NSMutableCharacterSet *characterSet = [NSMutableCharacterSet alphanumericCharacterSet];
[characterSet addCharactersInString:@"_"];

Swift

let characterSet = NSMutableCharacterSet.alphanumeric()
characterSet.addCharacters(in: "_")

You could verify it has been added (in a Playground) with:

characterSet.characterIsMember(UInt16(Character("^").unicodeScalars.first!.value)) // false
characterSet.characterIsMember(UInt16(Character("_").unicodeScalars.first!.value)) // true -- YAY!
characterSet.characterIsMember(UInt16(Character("`").unicodeScalars.first!.value)) // false

Solution 3 - Iphone

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSCharacterSet *blockedCharacters = [[NSCharacterSet whitespaceCharacterSet] invertedSet];
    NSCharacterSet *blockedCharacters2 = [[NSCharacterSet letterCharacterSet] invertedSet];
    return ([string rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound || [string rangeOfCharacterFromSet:blockedCharacters2].location);  

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontypeoneerrorView Question on Stackoverflow
Solution 1 - IphonedrawnonwardView Answer on Stackoverflow
Solution 2 - IphoneRuss Van BertView Answer on Stackoverflow
Solution 3 - IphoneAsbelKView Answer on Stackoverflow