iPhone开发应用关于邮箱合法行为代码实现案例是本文要介绍的内容,主要是来学习邮箱合法行为的判断,文中用两种方法来解决邮箱合法行为的问题,具体内容来看本文详细讲解。
1、判断邮箱合法行为的代码
如果你的 App 需要用户以邮箱注册,怎么判断用户输入了正确的邮箱地址呢?比如:用户输入了一长串字符,却没有 "@",或者字符串里有邮件地址里不允许包含的字符。favormm 的博客分享了判断邮箱是否合法的代码,希望对开发者有所帮助。
- BOOL NSStringIsValidEmail(NSString *checkString)
- {
- NString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
- NSString *laxString = @".+@.+\.[A-Za-z]{2}[A-Za-z]*";
- NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
- NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
- return [emailTest evaluateWithObject:checkString];
- }
2、另一组判断邮箱合法行为的代码
上面介绍的是判断邮箱合法行为的代码,下面介绍另一种方法,通过字符串操作来检查邮箱合法性。代码如下 :
- -(BOOL)validateEmail:(NSString*)email{
- 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;
- }
小结:iPhone开发应用关于邮箱合法行为代码实现案例的内容介绍完了,希望通过本文的学习能对你有所帮助!