I have a UITextfield that holds an username field, then I would like to add a validation so user cannot type a username that is different from letters, numbers and "_-." punctuation marks. I'm trying to use NSCharacterset to do that but without success.

NSScanner *scanner = [NSScanner scannerWithString:username];

NSCharacterSet *letterCharacterSet = [NSCharacterSet letterCharacterSet];
NSCharacterSet *decimalDigitCharacterSet = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *customPunctuationCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"_-."];

if (![scanner scanCharactersFromSet:letterCharacterSet intoString:NULL] &&
    ![scanner scanCharactersFromSet:customPunctuationCharacterSet intoString:NULL]&&
    ![scanner scanCharactersFromSet:decimalDigitCharacterSet intoString:NULL]){

    *error = [ScreenValidation createNSError:1 message:@"You can only use letters, numbers and punctuation marks."];
    return NO;

}

I realized that the result from the above code is not correct and as far as I know what I have to do is to concatenate all the NSCharacterSet into one to perform validation. Does anyone knows an elegant solution to that and of course that works with multiple locations.

Many thanks and Regards, Marcos

有帮助吗?

解决方案

The following will create a single character set from the three:

NSCharacterSet *letterCharacterSet = [NSCharacterSet letterCharacterSet];
NSCharacterSet *decimalDigitCharacterSet = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *customPunctuationCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"_-."];

NSMutableCharacterSet *validationCharacterSet = [letterCharacterSet mutableCopy];
[validationCharacterSet formUnionWithCharacterSet:decimalDigitCharacterSet];    
[validationCharacterSet formUnionWithCharacterSet:customPunctuationCharacterSet];

If you want to use this character set in multiple places you should add it as a global to some appropriate class. Another option is to create a category on NSCharacterSet and add it there.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top