Email Validation iPhone

The code I am using I found here:

if( (0 != [email rangeOfString:@"@"].length) &&  (0 != [email rangeOfString:@"."].length) )
NSMutableCharacterSet *invalidCharSet = [[[[NSCharacterSet alphanumericCharacterSet] invertedSet]mutableCopy]autorelease];
[invalidCharSet removeCharactersInString:@"_-"];

NSRange range1 = [email rangeOfString:@"@" options:NSCaseInsensitiveSearch];

// If username part contains any character other than "."  "_" "-"

NSString *usernamePart = [email substringToIndex:range1.location];
NSArray *stringsArray1 = [usernamePart componentsSeparatedByString:@"."];
for (NSString *string in stringsArray1) {
NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet: invalidCharSet];
if(rangeOfInavlidChars.length !=0 || [string isEqualToString:@""])
return NO;

NSString *domainPart = [email substringFromIndex:range1.location+1];
NSArray *stringsArray2 = [domainPart componentsSeparatedByString:@"."];

for (NSString *string in stringsArray2) {
NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet:invalidCharSet];
if(rangeOfInavlidChars.length !=0 || [string isEqualToString:@""])
return NO;

return YES;
else // no '@' or '.' present
return NO;

There is a thread on Stackoverflow suggesting another validation:

+(BOOL) validateEmail: (NSString *) email {
 NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
 NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
 BOOL isValid = [emailTest evaluateWithObject:email];
 return isValid;

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 )

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