views:

276

answers:

3

I am working on an iPhone application and need to make sure the entered text is composed of only a to z and numbers.

I don't want the user to use other languages letters like those with accents or dots above them.

EDIT: I am new to this RegEx, so if you please give me a code or a link, i will be really thankful.

+2  A: 

The simplest way - assuming you want to allow for punctuation as well is to check that all the characters are between ascii values 32 (space) and 126 (~). The ASCII table illustrates the point.

All the accented characters are what we used to call "high" ascii when I first started programming.

If you don't want to allow punctuation you'll have to do several range checks:

48 to 57 for numbers

65 to 90 for upper case

97 to 122 for lower case

which might make the RegEx approach more readable (I can't believe I just wrote that)

ChrisF
+8  A: 

Use a regular expression, like [0-9a-zA-Z]+. Check out the RegexKit Framework for Objective C, a regular expression library that works on the iPhone.

You can then do something like:

NSString *str = @"abc0129yourcontent";
BOOL isMatch = [str isMatchedByRegex:@"^[0-9a-zA-Z]+$"];
Wim Hollebrandse
+1  A: 

One more approach (may be not so elegant as with RegEx):

    NSCharacterSet* tSet = [NSCharacterSet characterSetWithCharactersInString:
               @"abcdefghijklmnopqrstuvxyz1234567890ABCDEFGHIJKLMNOPQRSTUVXYZ"];
    NSCharacterSet* invSet = [tSet invertedSet];
    NSString* legalS = @"abcdA1";
    NSString* illegalS = @"asvéq1";

    if ([legalS rangeOfCharacterFromSet:invSet].location != NSNotFound)
        NSLog(legalS); // not printed

    if ([illegalS rangeOfCharacterFromSet:invSet].location != NSNotFound)
        NSLog(illegalS); // printed
Vladimir
I like this solution too. Thanks
Adhamox