How to check if a string only contains alphanumeric characters in objective C?

Cheng Lai picture Cheng Lai · Nov 4, 2009 · Viewed 50k times · Source

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?

Answer

Jason Harwig picture Jason Harwig · Nov 4, 2009

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:@""];