iOS 中 textField 上的电子邮件验证

Posted

技术标签:

【中文标题】iOS 中 textField 上的电子邮件验证【英文标题】:Email validation on textField in iOS 【发布时间】:2011-07-22 15:32:38 【问题描述】:

ios App中,如何在UITextField上添加Email验证?

【问题讨论】:

ios-blog.co.uk/tutorials/quick-tips/… 【参考方案1】:

使用 NSPredicate 和正则表达式:

- (BOOL)validateEmailWithString:(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];

对于一堆用逗号分隔的电子邮件:

- (NSMutableArray*)validateEmailWithString:(NSString*)emails

    NSMutableArray *validEmails = [[NSMutableArray alloc] init];
    NSArray *emailArray = [emails componentsSeparatedByString:@","];
    for (NSString *email in emailArray)
    
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,4"; 
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
        if ([emailTest evaluateWithObject:email])
            [validEmails addObject:email];
    
    return [validEmails autorelease];

已编辑答案:(它还验证了额外的点)

- (BOOL)validateEmailWithString:(NSString*)checkString

    BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
    NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]2,4";
    NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]2[A-Za-z]*";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];

【讨论】:

@Prera​​k 请参阅上面我编辑的答案。这将返回一个包含所有有效电子邮件的数组。 我尝试使用电子邮件地址email@provider..comprovider 后面有两个点)测试这个正则表达式,它通过了。它是无效的电子邮件地址吗? 如何限制用户在文本字段中仅输入@gmail.com 的电子邮件ID。 also ' 是电子邮件地址中的有效字符。正则表达式应该是"[A-Z0-9a-z'._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,6" ' ' [空格] 在 emailId 中没有被识别为不正确的电子邮件,可以吗?【参考方案2】:

试试这个 这会准确检查***域名以及验证。


- (BOOL)validateEmail:(NSString *)inputText 
    NSString *emailRegex = @"[A-Z0-9a-z][A-Z0-9a-z._%+-]*@[A-Za-z0-9][A-Za-z0-9.-]*\\.[A-Za-z]2,6"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    NSRange aRange;
    if([emailTest evaluateWithObject:inputText]) 
        aRange = [inputText rangeOfString:@"." options:NSBackwardsSearch range:NSMakeRange(0, [inputText length])];
        int indexOfDot = aRange.location;
        //NSLog(@"aRange.location:%d - %d",aRange.location, indexOfDot);
        if(aRange.location != NSNotFound) 
            NSString *topLevelDomain = [inputText substringFromIndex:indexOfDot];
            topLevelDomain = [topLevelDomain lowercaseString];
            //NSLog(@"topleveldomains:%@",topLevelDomain);
            NSSet *TLD;
            TLD = [NSSet setWithObjects:@".aero", @".asia", @".biz", @".cat", @".com", @".coop", @".edu", @".gov", @".info", @".int", @".jobs", @".mil", @".mobi", @".museum", @".name", @".net", @".org", @".pro", @".tel", @".travel", @".ac", @".ad", @".ae", @".af", @".ag", @".ai", @".al", @".am", @".an", @".ao", @".aq", @".ar", @".as", @".at", @".au", @".aw", @".ax", @".az", @".ba", @".bb", @".bd", @".be", @".bf", @".bg", @".bh", @".bi", @".bj", @".bm", @".bn", @".bo", @".br", @".bs", @".bt", @".bv", @".bw", @".by", @".bz", @".ca", @".cc", @".cd", @".cf", @".cg", @".ch", @".ci", @".ck", @".cl", @".cm", @".cn", @".co", @".cr", @".cu", @".cv", @".cx", @".cy", @".cz", @".de", @".dj", @".dk", @".dm", @".do", @".dz", @".ec", @".ee", @".eg", @".er", @".es", @".et", @".eu", @".fi", @".fj", @".fk", @".fm", @".fo", @".fr", @".ga", @".gb", @".gd", @".ge", @".gf", @".gg", @".gh", @".gi", @".gl", @".gm", @".gn", @".gp", @".gq", @".gr", @".gs", @".gt", @".gu", @".gw", @".gy", @".hk", @".hm", @".hn", @".hr", @".ht", @".hu", @".id", @".ie", @" No", @".il", @".im", @".in", @".io", @".iq", @".ir", @".is", @".it", @".je", @".jm", @".jo", @".jp", @".ke", @".kg", @".kh", @".ki", @".km", @".kn", @".kp", @".kr", @".kw", @".ky", @".kz", @".la", @".lb", @".lc", @".li", @".lk", @".lr", @".ls", @".lt", @".lu", @".lv", @".ly", @".ma", @".mc", @".md", @".me", @".mg", @".mh", @".mk", @".ml", @".mm", @".mn", @".mo", @".mp", @".mq", @".mr", @".ms", @".mt", @".mu", @".mv", @".mw", @".mx", @".my", @".mz", @".na", @".nc", @".ne", @".nf", @".ng", @".ni", @".nl", @".no", @".np", @".nr", @".nu", @".nz", @".om", @".pa", @".pe", @".pf", @".pg", @".ph", @".pk", @".pl", @".pm", @".pn", @".pr", @".ps", @".pt", @".pw", @".py", @".qa", @".re", @".ro", @".rs", @".ru", @".rw", @".sa", @".sb", @".sc", @".sd", @".se", @".sg", @".sh", @".si", @".sj", @".sk", @".sl", @".sm", @".sn", @".so", @".sr", @".st", @".su", @".sv", @".sy", @".sz", @".tc", @".td", @".tf", @".tg", @".th", @".tj", @".tk", @".tl", @".tm", @".tn", @".to", @".tp", @".tr", @".tt", @".tv", @".tw", @".tz", @".ua", @".ug", @".uk", @".us", @".uy", @".uz", @".va", @".vc", @".ve", @".vg", @".vi", @".vn", @".vu", @".wf", @".ws", @".ye", @".yt", @".za", @".zm", @".zw", nil];
            if(topLevelDomain != nil && ([TLD containsObject:topLevelDomain])) 
                //NSLog(@"TLD contains topLevelDomain:%@",topLevelDomain);
                return TRUE;
            
            /*else 
             NSLog(@"TLD DOEST NOT contains topLevelDomain:%@",topLevelDomain);
             */

        
    
    return FALSE;


【讨论】:

您的***域集中有字符串@"No"。我认为那不应该在那里。此外,您的列表缺少一些官方***域,例如非拉丁语的。请参阅 iana.org/domains/root/db 了解官方 IANA 列表。 @Florian: .no 是一个有效的 TLD。它在挪威被大量使用。它甚至列在您链接到的资源中。例如:www.google.no 我说的不是@".no",而是@"No"。就在列表中的@".ie" 之后。 这不是一个好主意,这已经过时了,因为 .bike 和 .ventures TDL 以及数以千计的其他 TDL 已经在销售。 很好的答案 ...tnx 很多@SNR【参考方案3】:

使用下面的代码:-

NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,4";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
//Valid email address

if ([emailTest evaluateWithObject:userMailTextField.text] == YES) 

     //Do Something

else

     NSLog(@"email not in proper format");

userMailTextField 是我的 textField 的名称(使用您自己的)。

希望这段代码对你有帮助!!!

【讨论】:

感谢这个例子!真的太棒了! 我认为这应该是正确的答案。如果电子邮件地址中间有空格,则接受的答案失败。【参考方案4】:

“Swift 语言” 使用以下代码进行电子邮件验证

func ValidateEmailString (strEmail:NSString) -> Bool

   let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,4"
   let emailText = NSPredicate(format:"SELF MATCHES [c]%@",emailRegex)
   return (emailText.evaluate(with: strEmail))
 

谢谢:)

【讨论】:

不错的解决方案 Ilesh【参考方案5】:

NSRegularExpression 是在 iOS 4.x 及更高版本中使用Validate Email Addresses 的最佳方式。

-(BOOL) validateEmail:(NSString*) emailString 

     NSString *regExPattern = @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]2,4$";
     NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
     NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
     NSLog(@"%i", regExMatches);
     if (regExMatches == 0) 
         return NO;
      
     else
         return YES;

用法:

if([self validateEmail:@"something@domain.com"]) 
  //Email Address is valid.
 
else 
  //Email Address is invalid.

【讨论】:

聪明实用的答案+1【参考方案6】:
- (BOOL)validateEmailAddress:(NSString*)yourEmail

    //create a regex string which includes all email validation
    NSString *emailRegex    = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,4";

    //create predicate with format matching your regex string
    NSPredicate *email  = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    //return True if your email address matches the predicate just formed 
    return [email evaluateWithObject:yourEmail];`

【讨论】:

【参考方案7】:

--通过调用 validateEmail 方法很容易验证您的电子邮件 ID:

-(BOOL)validateEmail:(NSString *)email      

    NSString *emailRegex = @"[a-z0-9!#$%&'*+/=?^_`|~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`|~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";  

    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:email];

在此处验证您的电子邮件 ID....

BOOL eb=[self validateEmail:**youremailtextfield**];

if(!eb)

    UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Please enter correct email id"
                                                          delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

    [alertsuccess show];
    [alertsuccess release]; 

【讨论】:

【参考方案8】:

这是在 obj c 中验证电子邮件的简单方法

if(![self validEmail:self.emailTxtFld.text]) 
    // here show alert not a valid email id

这里是有效的电子邮件 ID 方法

- (BOOL) validEmail:(NSString*) emailString 
if([emailString length]==0)
    return NO;

NSString *regExPattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,4";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
     if (regExMatches == 0) 
         return NO;
      else 
             return YES;
       

Swift 3.0 版本中

if !validEmailId(inputText: userNameTxtFld.text!)  
        print("Not Valid Emaild")
    
else 
    print("valid email id")
    

func validEmailId(inputText: String)-> Bool 
    print("validate emilId: \(inputText)")
    let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'|~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'|~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]0,61[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]0,61[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.)3(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    let result = emailTest.evaluate(with: inputText)
    return result

【讨论】:

【参考方案9】:

这完全有效

-(BOOL) emailValidation:(NSString *)emailTxt

    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:emailTxt];


【讨论】:

【参考方案10】:

电子邮件的完美验证。试试这个。

- (BOOL)validateEmailWithString:(NSString*)checkString


    NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]2[A-Za-z]*";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", laxString];
    return [emailTest evaluateWithObject:checkString];

【讨论】:

【参考方案11】:

我是DCKit 库的作者,其中有DCMandatoryEmailTextField。此类自动进行电子邮件验证,并在用户输入值时突出显示/取消突出显示文本字段:

查看:https://github.com/andrew8712/DCKit

【讨论】:

【参考方案12】:

斯威夫特

func validateEmail(email:String) -> Bool 

    let stricterFilter = false
    let stricterFilterString = "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]2,4"
    let laxString = ".+@([A-Za-z0-9-]+\\.)+[A-Za-z]2[A-Za-z]*";
    let emailRegex = stricterFilter ? stricterFilterString : laxString
    let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)

    return emailTest.evaluate(with: email);

【讨论】:

【参考方案13】:

功能:

- (BOOL)validateEmail:(NSString *)enteredEmailID

    //checking valid email id or not
    NSString *emailReg = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,4";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailReg];
    return [emailTest evaluateWithObject:enteredEmailID];

这样称呼:

if ([self validateEmail: textField.text])
        
            //NSLog(@"Valid Email");
        
        else
        
            //NSLog(@"Invalid Email");
        

编辑: 您可以在文本字段中执行此操作并结束编辑代表或文本字段应字符更改代表

【讨论】:

【参考方案14】:

使用 NSRegularExpression 和从 OWASP_Validation_Regex_Repository 复制的正则表达式模式的版本

+ (BOOL) isValidEmail:(NSString *)emailString 
        NSError *error = NULL;
        /**
         * @see <a href="https://www.owasp.org/index.php/OWASP_Validation_Regex_Repository">OWASP_Validation_Regex_Repository</a>
         */
        NSString *emailPattern = @"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]2,7$";
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:emailPattern
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&error];
        NSUInteger matchCount = [regex numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
        return matchCount > 0;
    

【讨论】:

以上是关于iOS 中 textField 上的电子邮件验证的主要内容,如果未能解决你的问题,请参考以下文章

表单验证电子邮件地址

EditText 上的 Android 电子邮件验证

将电子邮件从身份验证列表发送给Firebase上的所有用户

为啥我无法在 Swift 的登录按钮中验证 textFields

PHPMailer 使用 SMTP 身份验证发送电子邮件,但 Gmail 仍然声称它无法验证发件人

ForEach 通过多个 TextField 来验证 SwiftUI 中是不是为空