代码:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.title=@"验证邮箱的合法性"; //最全面的验证邮箱的方法,用两种方法一起测试 NSString *email=@"618712810@.qq.com"; NSLog(@"---%i--",[self validateEmail:email]); if ([self validateEmail:email]&&[self isValidateEmail:email]) { NSLog(@"--此邮箱合法---"); }else { NSLog(@"--此邮箱不合法---"); } } //通过区分字符串 -(BOOL)validateEmail:(NSString*)email { if((0 != [email rangeOfString:@"@"].length) && (0 != [email rangeOfString:@"."].length)) { NSCharacterSet* tmpInvalidCharSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet]; NSMutableCharacterSet* tmpInvalidMutableCharSet = [tmpInvalidCharSet mutableCopy]; [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 { 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]; }
2014-11-20 16:22:17.999 验证邮箱的合法性[21525:60b] ---0--
2014-11-20 16:22:18.002 验证邮箱的合法性[21525:60b] --此邮箱不合法---