ios 如何快速验证电子邮件地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25471114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:01:25  来源:igfitidea点击:

How to validate an e-mail address in swift?

iosvalidationemailswift

提问by Giorgio Nocera

Does anyone know how to validate an e-mail address in Swift? I found this code:

有谁知道如何在 Swift 中验证电子邮件地址?我找到了这个代码:

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

    NSLog(@"%i", regExMatches);
    if (regExMatches == 0) {
        return NO;
    } else {
        return YES;
    }
}

but I can't translate it to Swift.

但我无法将其翻译成 Swift。

回答by Maxim Shoustin

I would use NSPredicate:

我会用NSPredicate

func isValidEmail(_ email: String) -> Bool {        
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64}"

    let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    return emailPred.evaluate(with: email)
}

for versions of Swift earlier than 3.0:

对于 3.0 之前的 Swift 版本:

func isValidEmail(email: String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64}"

    let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    return emailPred.evaluate(with: email)
}

for versions of Swift earlier than 1.2:

对于 1.2 之前的 Swift 版本:

func isValidEmail(email: String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64}"

    if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {
        return emailPred.evaluateWithObject(email)
    }
    return false
}

回答by Azik Abdullah

Editing, updated for Swift 3:

编辑,为 Swift 3 更新:

func validateEmail(enteredEmail:String) -> Bool {

    let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64}"
    let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
    return emailPredicate.evaluate(with: enteredEmail)

}

Original answer for Swift 2:

Swift 2 的原始答案:

func validateEmail(enteredEmail:String) -> Bool {

    let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64}"
    let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
    return emailPredicate.evaluateWithObject(enteredEmail)

}

It's working fine.

它工作正常。

回答by Arsonik

As a Stringclass extension

作为String类扩展

SWIFT 4

快速 4

extension String {
    func isValidEmail() -> Bool {
        // here, `try!` will always succeed because the pattern is valid
        let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[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])?)*$", options: .caseInsensitive)
        return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
    }
}

Usage

用法

if "rdfsdsfsdfsd".isValidEmail() {

}

回答by alexcristea

If you are looking for a clean and simple solution to do this, you should take a look at https://github.com/nsagora/validation-components.

如果您正在寻找一个干净简单的解决方案来执行此操作,您应该查看https://github.com/nsagora/validation-components

It contains an email validation predicate which is easy integrate in your code:

它包含一个电子邮件验证谓词,可以轻松集成到您的代码中:

let email = "[email protected]"
let rule = EmailValidationPredicate()
let isValidEmail = rule.evaluate(with: email)


Behind the hood it uses the RFC 5322 reg ex (http://emailregex.com):

在幕后,它使用 RFC 5322 reg ex ( http://emailregex.com):

let regex = "(?:[\p{L}0-9!#$%\&'*+/=?\^_`{|}~-]+(?:\.[\p{L}0-9!#$%\&'*+/=?\^_`{|}" +
    "~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\" +
    "x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[\p{L}0-9](?:[a-" +
    "z0-9-]*[\p{L}0-9])?\.)+[\p{L}0-9](?:[\p{L}0-9-]*[\p{L}0-9])?|\[(?:(?:25[0-5" +
    "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" +
    "9][0-9]?|[\p{L}0-9-]*[\p{L}0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21" +
    "-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"

回答by Fattie

Here's the reasonable solution:

这是合理的解决方案:

"THE REASONABLE SOLUTION"

“合理的解决方案”

Used and tested for years in many huge volume apps.

在许多大容量应用程序中使用和测试多年。

1 - it avoids the many terrible regex mistakesyou often see in these suggestions

1 - 它避免了您在这些建议中经常看到的许多可怕的正则表达式错误

2 - it does NOTallow stupid emails such as "x@x" which are thought to be valid under certain RFCs, but are completely silly, can't be used as emails, and which your support staff would reject instantly, and which all mailer services (mailchimp, google, aws, etc) simply reject. If (for some reason) you need a solution that allows strings such as 'x@x', use another solution.

2 -它不是让愚蠢的电子邮件,如“X @ X”,这被认为是在一定的RFC有效的,但完全傻了,无法使用电子邮件,并支持人员会立即拒绝,并全部邮件服务(mailchimp、google、aws 等)只是拒绝。如果(出于某种原因)您需要一个允许使用诸如 'x@x' 之类的字符串的解决方案,请使用其他解决方案。

3 - the code is very, very, very understandable

3 - 代码非常非常非常好理解

4 - it is KISS, reliable, and tested to destruction on commercial apps with enormous numbers of users

4 - 它是 KISS、可靠的,并且在拥有大量用户的商业应用程序上进行了破坏测试

5 - a technical point, the predicateis a global, as Apple saysit should be (watch out for code suggestions which don't have this)

5 - 一个技术点,谓词是一个全局的,正如苹果所说的那样(注意没有这个的代码建议)

let __firstpart = "[A-Z0-9a-z]([A-Z0-9a-z._%+-]{0,30}[A-Z0-9a-z])?"
let __serverpart = "([A-Z0-9a-z]([A-Z0-9a-z-]{0,30}[A-Z0-9a-z])?\.){1,5}"
let __emailRegex = __firstpart + "@" + __serverpart + "[A-Za-z]{2,8}"
let __emailPredicate = NSPredicate(format: "SELF MATCHES %@", __emailRegex)

extension String {
    func isEmail() -> Bool {
        return __emailPredicate.evaluate(with: self)
    }
}

extension UITextField {
    func isEmail() -> Bool {
        return self.text!.isEmail()
    }
}

It's that easy.

就这么简单。

Explanation:

解释:

In the following description, "OC" means ordinary character - a letter or a digit.

在以下描述中,“OC”表示普通字符——字母或数字。

__firstpart ... has to start and endwith an OC. For the characters in the middleyou can have certaincharacters such as underscore, but the start and endhave to be an OC. (However, it's okto have only one OC and that's it, for example: [email protected])

__firstpart ... 必须以OC开始和结束。对于中间的字符,您可以使用某些字符,例如下划线,但开头和结尾必须是 OC。(然而,这是确定只生一个OC,就是这样,例如:[email protected]

__serverpart ... You have sectionslike "blah." which repeat. (So mail.city.fcu.edu type of thing.) The sections have to start and endwith an OC, but in the middleyou can also have a dash"-". (If you want to allow otherunusual characters in there, perhaps the underscore, simply add before the dash.) It's OKto have a section which is just oneOC. (As in [email protected]) You can have up to five sections, you have tohave one. Finally the TLD(such as .com) is strictly 2 to 8 in size. Obviously, just change that "8" as preferred by your support department.

__serverpart ... 你有像“blah”这样的部分。其中重复。(所以 mail.city.fcu.edu 类型的东西。)这些部分必须以OC开始和结束,但在中间你也可以有一个破折号“-”。(如果你想允许其他的有特殊字符,或许下划线,只需将破折号前增加)。它的确定有一个节这只是一个OC。(如 [email protected])你最多可以有五个部分,你必须有一个。最后TLD(例如.com)是严格2〜8在尺寸. 显然,只需根据您的支持部门的喜好更改“8”。



IMPORTANT !

重要的 !

You must keep the predicate as a global, do not build it every time.

您必须将谓词保持为全局,不要每次都构建它。

Note that this is the first thing Apple mentions about the whole issuein the docs.

请注意,这是Apple在文档中提到的关于整个问题的第一件事

It's very surprising when you see suggestions which do not cache the predicate.

当您看到不缓存谓词的建议时,这是非常令人惊讶的。

回答by Nicolas Manzini

Here is a fuse of the two most up-voted answer with the correct regex: a String extension using predicate so you can call string.isEmail

这是两个最受好评的答案与正确正则表达式的融合:使用谓词的字符串扩展,因此您可以调用 string.isEmail

    extension String {
        var isEmail: Bool {
           let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,20}"            
           let emailTest  = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
           return emailTest.evaluateWithObject(self)
        }
    }

回答by Ken Mueller

Simplest way in Swift 5

Swift 5 中最简单的方法

extension String {
    var isValidEmail: Bool {
        NSPredicate(format: "SELF MATCHES %@", "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}").evaluate(with: self)
    }
}

Example

例子

"[email protected]".isValidEmail

returns...

返回...

true

回答by JeffersonBe

I would suggest using it as an extension of String:

我建议将它用作 String 的扩展:

extension String {    
    public var isEmail: Bool {
        let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)

        let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length))

        return (firstMatch?.range.location != NSNotFound && firstMatch?.url?.scheme == "mailto")
    }

    public var length: Int {
        return self.characters.count
    }
}

And to use it:

并使用它:

if "[email protected]".isEmail { // true
    print("Hold the Door")
}

回答by Joel García Verástica

This is the updated version for Swift 2.0 - 2.2

这是 Swift 2.0 - 2.2 的更新版本

 var isEmail: Bool {
    do {
        let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[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])?)*$", options: .CaseInsensitive)
        return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
    } catch {
        return false
    }
}

回答by Andrea.Ferrando

There are a lot of right answers here, but many of the "regex" are incomplete and it can happen that an email like: "name@domain" results a valid email, but it is not. Here the complete solution:

这里有很多正确的答案,但许多“正则表达式”是不完整的,并且可能发生这样的电子邮件:“name@domain”会产生有效的电子邮件,但事实并非如此。这里是完整的解决方案:

extension String {

    var isEmailValid: Bool {
        do {
            let regex = try NSRegularExpression(pattern: "(?:[a-z0-9!#$%\&'*+/=?\^_`{|}~-]+(?:\.[a-z0-9!#$%\&'*+/=?\^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])", options: .CaseInsensitive)
            return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
        } catch {
            return false
        }
    }
}