Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if NSString contains alphanumeric + underscore characters only

I've got a string that needs to be only a-z, 0-9 and _

How do I check if the input is valid? I've tried this but it accepts letter like å,ä,ö,ø etc.

NSString *string = [NSString stringWithString:nameField.text];
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
[string stringByTrimmingCharactersInSet:alphaSet];
[string stringByReplacingOccurrencesOfString:@"_" withString:@""];
BOOL valid = [[string stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
like image 907
David Avatar asked Sep 25 '11 14:09

David


3 Answers

You can create your own character set:

NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];

Once you have that, you invert it to everything that's not in your original string:

s = [s invertedSet];

And you can then use a string method to find if your string contains anything in the inverted set:

NSRange r = [string rangeOfCharacterFromSet:s];
if (r.location != NSNotFound) {
  NSLog(@"the string contains illegal characters");
}
like image 116
Dave DeLong Avatar answered Oct 19 '22 21:10

Dave DeLong


You can use a predicate:

NSString *myRegex = @"[A-Z0-9a-z_]*"; 
NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", myRegex]; 
NSString *string = nameField.text;
BOOL valid = [myTest evaluateWithObject:string];

Edit: I don't noticed that you are using [NSString stringWithString:nameField.text].

Use nameField.text instead.

like image 38
Sinetris Avatar answered Oct 19 '22 20:10

Sinetris


Some more easy way,

NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:@"_"];
[allowedSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
NSCharacterSet *forbiddenSet = [allowedSet invertedSet];

It'll combine alphanumeric along with _underscore.

you can use it like,

NSRange r = [string rangeOfCharacterFromSet:forbiddenSet];
if (r.location != NSNotFound) {
  NSLog(@"the string contains illegal characters");
}

PS. example copied from @DaveDeLong example :)

like image 10
Hemang Avatar answered Oct 19 '22 19:10

Hemang