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

Solution 1:

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

Solution 2:

This will work:

@implementation NSString (alphaOnly)

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

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

@end

Solution 3:

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

^[a-zA-Z0-9]*$

Solution 4:

The NSCharacterSet based answers do not give the results you might expect for Japanese etc text, often claiming that they do contain alphanumeric characters - the test being performed boils down to 'are there only letters or numbers', and Japanese (etc) characters count as 'Letters'.

If you're trying to check Latin characters vs a foreign language (eg. Japanese), then the answer from " How to determine if an NSString is latin based? " may help:

BOOL isLatin = [myString canBeConvertedToEncoding:NSISOLatin1StringEncoding];

NSASCIIStringEncoding could also be used instead of NSISOLatin1StringEncoding to further restrict the valid characters. You could also test using NSCharacterSet afterwards, to exclude special characters like !, #, etc.