Check if NSString contains alphanumeric and underscore characters only

In iPhone on September 25, 2011 by patrellery Tagged: ,

Having an iPhone app is a great way to have a mobile version of your site or software. It can increase your market and be up-to-date on the market. If you have a software that requires login you might need to match the validation of your web app vs your iPhone app.

Let’s say you need to validate if a string contains only letter, numbers and underscores for your login page. You want to make sure the iPhone version match the username of your web version.

So you have code like:
NSString *string = [NSString stringWithString:nameField.text];
NSCharacterSet *alpha = [NSCharacterSet alphanumericCharacterSet];
[string stringByTrimmingCharactersInSet:alpha ];
[string stringByReplacingOccurrencesOfString:@"_" withString:@""];
BOOL valid = [[string stringByTrimmingCharactersInSet:alpha ] isEqualToString:@""];

But this code does not validate what you need. Here’s a little script that will:

NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];
s = [s invertedSet];
NSRange r = [string rangeOfCharacterInSet:s];
if (r.location != NSNotFound) {
NSLog(@"the string contains illegal characters);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: