views:

1113

answers:

2

Hi all,

I want to check an NSString for special characters, i.e. anything expect a-z, A-Z and 0-9.

I don't need to check how many special characters are present, or their positions, I just need to know whether a particular string contains any or not. If it does, then I want to be able to display "Error!", or something similar.

e.g. jHfd9982 is OK, asdJh992@ is not.

Also, letters with accents, umlauts etc should not be allowed.

How would I go about this?

Thanks!

Michael

+2  A: 

You want to search NSString using a character set if it cant find any characters in the string then rangeOfCharacterFromSet: will return a range of {NSNotFound, 0}

The character set would be like [NSCharacterSet symbolCharacterSet] or your own set. Note you can also invert character sets so you could have a set of acceptable characters

Mark
+2  A: 
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789"] invertedSet];

if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
  NSLog(@"This string contains illegal characters");
}

You could also use a regex (this syntax is from RegexKitLite: http://regexkit.sourceforge.net ):

if ([aString isMatchedByRegex:@"[^a-zA-Z0-9]"]) {
  NSLog(@"This string contains illegal characters");
}
Dave DeLong