方法一:通过区分字符串
-(BOOL)validateEmail:(NSString*)email
{
if((0 != [email rangeOfString:@"@"].length) &&
(0 != [email rangeOfString:@"."].length))
{
NSCharacterSet* tmpInvalidCharSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSMutableCharacterSet* tmpInvalidMutableCharSet = [[tmpInvalidCharSet mutableCopy] autorelease];
[tmpInvalidMutableCharSet removeCharactersInString:@"_-"];
/*
*使用compare option 来设定比较规则,如
*NSCaseInsensitiveSearch是不区分大小写
*NSLiteralSearch 进行完全比较,区分大小写
*NSNumericSearch 只比较定符串的个数,而不比较字符串的字面值
*/
NSRange range1 = [email rangeOfString:@"@"
options:NSCaseInsensitiveSearch];
//取得用户名部分
NSString* userNameString = [email substringToIndex:range1.location];
NSArray* userNameArray = [userNameString componentsSeparatedByString:@"."];
for(NSString* string in userNameArray)
{
NSRange rangeOfInavlidChars = [string rangeOfCharacterFromSet: tmpInvalidMutableCharSet];
if(rangeOfInavlidChars.length != 0 || [string isEqualToString:@""])
return NO;
}
//取得域名部分
NSString *domainString = [email substringFromIndex:range1.location+1];
NSArray *domainArray = [domainString componentsSeparatedByString:@"."];
for(NSString *string in domainArray)
{
NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet:tmpInvalidMutableCharSet];
if(rangeOfInavlidChars.length !=0 || [string isEqualToString:@""])
return NO;
}
return YES;
}
else {
return NO;
}
}
方法二:利用正则表达式验证
-(BOOL)isValidateEmail:(NSString *)email {
/*电信号段:133/153/180/181/189/177
联通号段:130/131/132/155/156/185/186/145/176
移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
虚拟运营商:170
*/
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:email];
}