IPhone DevelopmentAbout applicationsValid Email actionsThe code implementation case is the content to be introduced in this article. It is mainly used to learn the judgment of valid mailbox behaviors. This article uses two methods to solve this problem.Valid Email actionsFor more information, see this article.
1. code used to determine valid mailbox Behaviors
If your App requires a user to register by email, how can you determine that the user has entered the correct email address? For example, if you enter a long string without "@", or the string contains characters not allowed in the email address. The favormm blog shares code to determine whether the email address is valid, hoping to help developers.
- 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. Another group of codes used to determine valid mailbox Behaviors
The above describes the code used to determine the valid behaviors of a mailbox. Next we will introduce another method to check the legitimacy of a mailbox through string operations. The Code is as follows:
- -(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;
- }
Summary:IPhone DevelopmentAbout applicationsValid Email actionsThe content of the code implementation case has been introduced. I hope this article will help you!