views:

2170

answers:

4

I'm working on a small iphone project and i would need to check if the userName entered only contains alphanumerical characters? (A-Z, a-z, 0-9). How would i go about checking it?

+2  A: 

You can use this regular expression library for ObjectiveC. Use the following regex to match:

^[a-zA-Z0-9]*$
Soviut
Not wrong, but really overkill.
Chuck
+6  A: 

If you don't want to bring in a regex library for this one task...

NSString *str = @"aA09";
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
BOOL valid = [[str stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
Jason Harwig
thz alot dude i was thinking something along the same line as you, but just couldn't figure out how
DrkZeraga
+6  A: 

This will work:

@implementation NSString (alphaOnly)

- (BOOL) isAlphaNumeric
   {
    NSCharacterSet *unwantedCharacters = 
       [[NSCharacterSet alphanumericCharacterSet] invertedSet];

    return ([self rangeOfCharacterFromSet:unwantedCharacters].location == NSNotFound) ? YES : NO;
    }

@end
NSResponder
The `? YES : NO` isn't really necessary. The result of a logical comparison is already a boolean value.
Chuck
I know, I just like to see it so that I don't read it later and think I left something out.
NSResponder
hey that's nice too man i didn't know u could invert the character set. lol wonder how does that work for other languages like Chinese
DrkZeraga
Works the same for all character sets. Unicode is well-supported in Cocoa.
NSResponder
While not flagged to be the answer by the poster, I like this solution better than one marked as the answer. It's really useful and can be extended easily for testing against other character sets as well. Thumb up.
+1  A: 

I really like the RegexKit Lite Framework. It uses the ICU regex library, which is already included with OSX and is unicode-safe.

NSString *str = @"testString";
[str isMatchedByRegex:@"^[a-zA-Z0-9]*$"]; // strict ASCII-match
[str isMatchedByRegex:@"^[\p{L}\p{N}]*$"]; // unicode letters and numbers match
Adrian