Question

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.

Was it helpful?

Solution

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]+$"];

OTHER TIPS

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

    NSCharacterSet* tSet = [NSCharacterSet characterSetWithCharactersInString:
               @"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
    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

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)

Easy implementation (take from above, edited just for fast copy-paste):

Objective-C:

BOOL onlyEnglishAlphanumerical = ([self.textField.text rangeOfCharacterFromSet:[[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet]].location == NSNotFound);
self.textField.layer.borderWidth = (onlyEnglishAlphanumerical) ? 0 : 1;
if (onlyEnglishAlphanumerical)
{
    //Do the deal
}

Swift:

if (self.textField.text.rangeOfCharacterFromSet(NSCharacterSet.init(charactersInString:"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ").invertedSet) == nil)
{
    //Do the deal
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top