如何在swift中验证电子邮件地址?

时间:2014-08-24 11:15:59

标签: ios validation email swift

有谁知道如何在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;
    }
}

但我无法将其翻译为Swift。

36 个答案:

答案 0 :(得分:672)

我会使用NSPredicate

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

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

对于早于3.0的Swift版本:

 func isValidEmail(testStr:String) -> Bool {

    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

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

对于早于1.2的Swift版本:

 class func isValidEmail(testStr:String) -> Bool {

    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

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

答案 1 :(得分:102)

编辑,更新为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.evaluateWithObject(enteredEmail)

}

Swift 2的原始答案:

{{1}}

工作正常。

答案 2 :(得分:100)

作为String类扩展名

SWIFT 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
    }
}

用法

if "rdfsdsfsdfsd".isValidEmail() {

}

答案 3 :(得分:43)

如果您正在寻找一个简洁明了的解决方案,那么您应该看看https://github.com/nsagora/validation-components

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

let email = "test@example.com"
let rule = EmailValidationPredicate()
let isValidEmail = rule.evaluate(with: email)

在幕后它使用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])+)\\])"

答案 4 :(得分:24)

这是使用正确的正则表达式的两个最高投票答案的融合:使用谓词的字符串扩展,因此您可以调用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)
        }
    }

答案 5 :(得分:24)

这是合理的解决方案:

“合理的解决方案”

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

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

2 - 它确实允许愚蠢的电子邮件,例如“x @ x”,这些电子邮件在技术上是有效的,但是非常愚蠢 - 而且您的支持人员无论如何都会立即拒绝。如果您需要一个允许愚蠢电子邮件的解决方案,请使用其他解决方案。

3 - 代码非常可以理解

4 - KISS,可靠,并且 在拥有大量用户的商业应用中进行了破坏测试

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()
    }
}

说明:

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

__ firstpart ...必须以OC开始和结束。对于中间的字符,你可以有一些不寻常的字符,如下划线,但开始和结束必须是OC。 (但是 - 请注意括号 - 只有一个OC就可以了,例如:j@blah.com)

__ serverpart ...你有像“blah”这样的部分。重复一遍。 (所以mail.city.fcu.edu类型的东西。)部分必须以OC开头和结尾,但在中间你也可以有一个短划线“ - ”。 (如果你想在那里允许其他不寻常的字符,比如下划线,只需在短划线前添加。)可以有一个只有一个OC的部分。 (如joe@w.campus.edu)你最多可以有五个部分;你必须有一个。最后,TLD(例如.com)的大小严格为2到8个。

!!重要!!

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

!!请注意,这是Apple在doco中提到的第一件事!!

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

答案 6 :(得分:15)

这是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
    }
}

答案 7 :(得分:14)

我建议将它用作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
    }
}

使用它:

if "hodor@gameofthrones.com".isEmail { // true
    print("Hold the Door")
}

答案 8 :(得分:8)

以下是基于rangeOfString的方法:

class func isValidEmail(testStr:String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
    let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
    let result = range != nil ? true : false
    return result
}

注意:更新的TLD长度。

根据RFC 5322,这是电子邮件的权威RegEx,请注意,最好不要使用它,因为它只检查电子邮件地址的基本语法,而不检查是否存在顶级域名。

(?:[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])+)
     \])

有关电子邮件RegEx的更多完整信息,请参阅Regular-Expressions.info

请注意,不要使用Objective-C或Swift等语言进行转义。

答案 9 :(得分:7)

我更喜欢使用扩展名。此外,此网址http://emailregex.com可以帮助您测试正则表达式是否正确。实际上,该站点为某些编程语言提供了不同的实现。我分享了 Swift 3 的实现。

extension String {
    func validateEmail() -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
        return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
    }
}

答案 10 :(得分:7)

这里有很多正确的答案,但许多&#34;正则表达式&#34;是不完整的,可能会发生如下电子邮件:&#34; name @ domain&#34;结果有效的电子邮件,但事实并非如此。这里有完整的解决方案:

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
        }
    }
}

答案 11 :(得分:6)

对于swift 2.1:这适用于电子邮件foo @ bar

extension String {
    func isValidEmail() -> Bool {
        do {
            let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}", options: .CaseInsensitive)
            return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
        } catch {
                return false
        }
    }
}

答案 12 :(得分:5)

使用Swift 4.2

extension String {
    func isValidEmail() -> Bool {
        let regex = try? NSRegularExpression(pattern: "^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$", options: .caseInsensitive)
        return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.count)) != nil
    }
    func isValidName() -> Bool{
        let regex = try? NSRegularExpression(pattern: "^[\\p{L}\\.]{2,30}(?: [\\p{L}\\.]{2,30}){0,2}$", options: .caseInsensitive)

        return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.count)) != nil
    } }

二手

if (textField.text?.isValidEmail())! 
    {
      // bla bla
    }
else 
    {

    }

答案 13 :(得分:3)

创建简单的扩展名:

byte[] buffer = ...
var bitmap = new BitmapImage();

using (var memoryStream = new MemoryStream(buffer))
{
    bitmap.SetSource(memoryStream);
}

示例:

extension NSRegularExpression {

    convenience init(pattern: String) {
        try! self.init(pattern: pattern, options: [])
    }
}

extension String {

    var isValidEmail: Bool {
        return isMatching(expression: NSRegularExpression(pattern: "^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$"))
    }

    //MARK: - Private

    private func isMatching(expression: NSRegularExpression) -> Bool {
        return expression.numberOfMatches(in: self, range: NSRange(location: 0, length: characters.count)) > 0
    }
}

您可以将以下扩展程序扩展为您需要的任何内容:"b@bb.pl".isValidEmail //true "b@bb".isValidEmail //false isValidPhoneNumber等...

答案 14 :(得分:3)

@Fattie的&#34;合理解决方案&#34; 的新版本,在名为String+Email.swift的新文件中在Swift 4.1上进行了测试:

import Foundation

extension String {
    private static let __firstpart = "[A-Z0-9a-z]([A-Z0-9a-z._%+-]{0,30}[A-Z0-9a-z])?"
    private static let __serverpart = "([A-Z0-9a-z]([A-Z0-9a-z-]{0,30}[A-Z0-9a-z])?\\.){1,5}"
    private static let __emailRegex = __firstpart + "@" + __serverpart + "[A-Za-z]{2,6}"

    public var isEmail: Bool {
        let predicate = NSPredicate(format: "SELF MATCHES %@", type(of:self).__emailRegex)
        return predicate.evaluate(with: self)
    }
}

所以它的用法很简单:

let str = "mail@domain.com"
if str.isEmail {
    print("\(str) is a valid e-mail address")
} else {
    print("\(str) is not a valid e-mail address")
}

我只是不想在func对象中添加String,因为电子邮件地址是他们固有的(或不是)。因此,根据我的理解,Bool属性比func更适合。

答案 15 :(得分:2)

Swift 4.2 和Xcode 10.1

//Email validation
func isValidEmail(email: String) -> Bool {
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
    if valid {
        valid = !email.contains("Invalid email id")
    }
    return valid
}

//Use like this....
let emailTrimmedString = emailTF.text?.trimmingCharacters(in: .whitespaces)
if isValidEmail(email: emailTrimmedString!) == false {
   SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter valid email")
}

如果要使用SharedClass。

//This is SharedClass
import UIKit
class SharedClass: NSObject {

static let sharedInstance = SharedClass()

//Email validation
func isValidEmail(email: String) -> Bool {
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
    if valid {
        valid = !email.contains("Invalid email id")
    }
    return valid
}

private override init() {

}
}

然后调用这样的函数。...

if SharedClass.sharedInstance. isValidEmail(email: emailTrimmedString!) == false {
   SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter correct email")
   //Your code here
} else {
   //Code here
}

答案 16 :(得分:2)

我创建了一个专为输入验证设计的库和一个&#34;模块&#34;允许您轻松验证一堆东西...

例如,验证电子邮件:

let emailTrial = Trial.Email
let trial = emailTrial.trial()

if(trial(evidence: "test@test.com")) {
   //email is valid
}

SwiftCop是图书馆......希望它有所帮助!

答案 17 :(得分:1)

Swift 5中最简单的方法

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

示例

"kenmueller0@gmail.com".isValidEmail

返回...

true

答案 18 :(得分:0)

这是Swift 3的扩展

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

就这样使用它:

if yourEmailString.isValidEmail() {
    //code for valid email address
} else {
    //code for not valid email address
}

答案 19 :(得分:0)

Swift 5电子邮件验证程序-正则表达式

这种实现具有其功能,可以非常简单地用作字符串扩展,很好的验证,并且是对RFC 2822的完整验证。

步骤1)文件->新建->文件...-> Swift文件并复制此代码:

import Foundation

extension String {

    // Checks if the `String` is a valid email address.
    func isValidEmailAddress() -> Bool {
        let emailRegEx = "(?:[a-zA-Z0-9!#$%\\&‘*+/=?\\^_`{|}~-]+(?:\\.[a-zA-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])+)\\])"

        let emailTest = NSPredicate(format: "SELF MATCHES[c] %@", emailRegEx)
        return emailTest.evaluate(with: self)
    }
}

第2步)将电子邮件验证程序用作字符串排除

@IBAction func sendEmail(_ sender: Any) {
    if let textFieldText = emailTextField.text, textFieldText.isValidEmailAddress() {
        // APICall or present next desired view controller
    } else {
        // Present an alert to tell user that is invalid email
    }
}

示例:

  • doc@mail.com->有效
  • doc@mail.com.au->有效
  • doc @ .com->无效
  • doc @ com->无效
  • doc.com->无效

来源:GitHub link

答案 20 :(得分:0)

对于仍在寻找答案的任何人,请查看以下框架;

ATGValidator

这是一个基于规则的验证框架,可立即处理大多数验证。最重要的是,它具有form validator,它支持同时验证多个文本字段。

要验证电子邮件字符串,请使用以下内容;

"abcd.hhs@some.com".satisfyAll(rules: [StringRegexRule.email]).status

如果您要验证来自文本字段的电子邮件,请尝试以下代码;

textfield.validationRules = [StringRegexRule.email]
textfield.validationHandler = { result in
    // This block will be executed with relevant result whenever validation is done.
    print(result.status, result.errors)
}
// Below line is to manually trigger validation.
textfield.validateTextField()

如果要在输入文本字段或将焦点更改为另一个字段时进行验证,请添加以下行之一;

textfield.validateOnInputChange(true)
// or
textfield.validateOnFocusLoss(true)

请查看link上的自述文件以了解更多用例。

答案 21 :(得分:0)

我改进了@Azik的答案。我允许指南允许的更多特殊字符,以及返回一些额外的边缘情况作为无效。

根据指南,小组认为此处只允许._%+-在本地部分不正确。请参阅this问题的@Anton Gogolev答案,或参见下文:

  

电子邮件地址的本地部分可以使用这些ASCII中的任何一种   字符:

     
      
  • 大写和小写拉丁字母AZaz;

  •   
  • 位数09;

  •   
  • 特殊字符!#$%&'*+-/=?^_`{|}~;

  •   
  • .,前提是它不是引用的第一个或最后一个字符,并且除非引用,否则它不会连续出现(例如,   John..Doe@example.com不允许"John..Doe"@example.com   允许);

  •   
  • 允许使用空格和"(),:;<>@[\]个字符   限制(它们只允许在带引号的字符串中使用,如   在下面的段落中描述,另外,反斜杠或   双引号必须以反斜杠开头);   允许评论

  •   
  • 在本地部分的两端加上括号;例如   john.smith(comment)@example.com(comment)john.smith@example.com   都等同于john.smith@example.com;

  •   

我使用的代码不允许限制不合适的特殊字符,但会允许比这里的大多数答案更多的选项。我希望在谨慎方面更轻松地验证错误。

if enteredText.contains("..") || enteredText.contains("@@") 
   || enteredText.hasPrefix(".") || enteredText.hasSuffix(".con"){
       return false
}

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: enteredText)

答案 22 :(得分:0)

我想创建扩展程序

   extension String {

func isValidateEmail() -> 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: self)
}

}

用法:

if emailid.text!.isValidateEmail() == false(){
 //do what ever you want if string is not matched.

}

答案 23 :(得分:0)

的最佳解决方案
  

Swift 4.x

 extension String {

        func validateAsEmail() -> Bool {
            let emailRegEx = "(?:[a-zA-Z0-9!#$%\\&‘*+/=?\\^_`{|}~-]+(?:\\.[a-zA-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])+)\\])"

            let emailTest = NSPredicate(format:"SELF MATCHES[c] %@", emailRegEx)
            return emailTest.evaluate(with: self)
        }
    }

答案 24 :(得分:0)

//Email validation
func validateEmail(enterEmail: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:enterEmail)
}

100%正常工作并经过测试

答案 25 :(得分:0)

快速5

 func isValidEmailAddress(emailAddressString: String) -> Bool {

 var returnValue = true
 let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"

 do {
        let regex = try NSRegularExpression(pattern: emailRegEx)
        let nsString = emailAddressString as NSString
        let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        {
            returnValue = false
        }

    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    }

    return  returnValue
}

然后:

let validEmail = isValidEmailAddress(emailAddressString: "your@email.com")
print(validEmail)

答案 26 :(得分:0)

我对回复列表的唯一补充是,对于Linux,NSRegularExpression不存在,实际上是RegularExpression

    func isEmail() -> Bool {

    let patternNormal = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"

    #if os(Linux)
        let regex = try? RegularExpression(pattern: patternNormal, options: .caseInsensitive)
    #else
        let regex = try? NSRegularExpression(pattern: patternNormal, options: .caseInsensitive)
    #endif

    return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.characters.count)) != nil

这在macOS&amp; Ubuntu的。

答案 27 :(得分:0)

Swift 3

extension String {
    func isValidEmail() -> Bool {
        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: NSMakeRange(0, self.characters.count)) != nil
    }
}

答案 28 :(得分:0)

@ JeffersonBe的回答很接近,但如果字符串是&#34;那么包含someone@something.com的有效电子邮件&#34;则会返回true。这不是我们想要的。以下是String的扩展,运行良好(并允许测试有效的phoneNumber和其他数据检测器启动。

/// Helper for various data detector matches.
/// Returns `true` iff the `String` matches the data detector type for the complete string.
func matchesDataDetector(type: NSTextCheckingResult.CheckingType, scheme: String? = nil) -> Bool {
    let dataDetector = try? NSDataDetector(types: type.rawValue)
    guard let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length)) else {
        return false
    }
    return firstMatch.range.location != NSNotFound
        // make sure the entire string is an email, not just contains an email
        && firstMatch.range.location == 0
        && firstMatch.range.length == length
        // make sure the link type matches if link scheme
        && (type != .link || scheme == nil || firstMatch.url?.scheme == scheme)
}
/// `true` iff the `String` is an email address in the proper form.
var isEmail: Bool {
    return matchesDataDetector(type: .link, scheme: "mailto")
}
/// `true` iff the `String` is a phone number in the proper form.
var isPhoneNumber: Bool {
    return matchesDataDetector(type: .phoneNumber)
}
/// number of characters in the `String` (required for above).
var length: Int {
    return self.characters.count
}

答案 29 :(得分:0)

更新了答案@Arsonik回答Swift 2.2,使用的代码比其他解决方案更简洁:

extension String {
    func isValidEmail() -> Bool {
        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: [], range: NSMakeRange(0, self.characters.count)) != nil
    }
}

答案 30 :(得分:0)

由于现在有这么多奇怪的顶级域名,我停止检查顶级域名的长度......

以下是我使用的内容:

extension String {

    func isEmail() -> Bool {
        let emailRegEx = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"
        return NSPredicate(format:"SELF MATCHES %@", emailRegEx).evaluateWithObject(self)
    } 
}

答案 31 :(得分:0)

似乎也有效......

let regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"

func validate(email: String) -> Bool {
    let matches = email.rangeOfString(regex, options: .RegularExpressionSearch)
    if let _ = matches {
        return true
    }
    return false
}

答案 32 :(得分:-1)

或者您可以对UITextField的可选文本进行扩展:

使用方法:

[
  {
    "id": 1,
    "name": "Asna",
    "Address": "NY",
    "Phone": 123
  },
  {
    "id": 2,
    "name": "Euphoria",
    "Address": "Monaco",
    "Phone": 124
  },
  {
    "id": 3,
    "name": "Ahmed",
    "Address": "Mumbai",
    "Phone": 125
  }
]

延伸:

if  emailTextField.text.isEmailValid() {
      print("email is valid")
}else{
      print("wrong email address")
}

答案 33 :(得分:-1)

这是当前Swiftmailer中可用的一种非常简单的方法。其他大多数答案都是过时的,并且彻底改变了方向。

根据Swiftmailer文档: https://swiftmailer.symfony.com/docs/messages.html#quick-reference

use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;

$validator = new EmailValidator();
$validator->isValid("example@example.com", new RFCValidation()); //true

这是迄今为止最简单,最可靠的方法imo。只需通过Composer安装Egulias \ EmailValidator库,该库应该已经作为SwiftMailer的依赖项引入了。

答案 34 :(得分:-2)

像Google电子邮件这样的完美正则表达式

"^[A-Z0-9a-z][a-zA-Z0-9_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"

答案 35 :(得分:-2)

Swift 5 - 可扩展的验证层

使用此层,您将轻松获得对任何文本字段的惊人验证。

只需按照以下流程操作即可。

1.添加这些枚举:

import Foundation

enum ValidatorType
{
    case email
    case name
    // add more cases ...
}

enum ValidationError: Error, LocalizedError
{
    case invalidUserName
    case invalidEmail
    // add more cases ...

    var localizedDescription: String
    {
        switch self
        {
        case .invalidEmail:
            return "Please kindly write a valid email"    
        case .invalidUserName:
            return "Please kindly write a valid user name"
        }
    }
}

2.将此功能添加到 String

extension String
{
    // MARK:- Properties

    var isValidEmail: 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: self)
    }

    // MARK:- Methods

    func validatedText(_ validationType: ValidatorType) throws
    {
        switch validationType
        {
            case .name:
                try validateUsername()
            case .email:
                try validateEmail()
        }
    }

    // MARK:- Private Methods

    private func validateUsername() throws
    {
        if isEmpty
        {
            throw ValidationError.invalidUserName
        }
    }

    private func validateEmail() throws
    {
        if !isValidEmail 
        {
            throw ValidationError.invalidEmail
        }

        // add more validations if you want like empty email
    }
}

3.将以下功能添加到 UITextField

import UIKit

extension UITextField
{
    func validatedText(_ validationType: ValidatorType) throws
    {
        do
        {
            try text?.validatedText(validationType)
        }
        catch let validationError
        {
            shake()
            throw validationError
        }
    }

    // MARK:- Private Methods

    private func shake()
    {
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.1
        animation.repeatCount = 5
        animation.fromValue = NSValue(cgPoint: CGPoint(x: center.x + 6, y: center.y))
        animation.toValue = NSValue(cgPoint: CGPoint(x: center.x - 6, y: center.y))
        layer.add(animation, forKey: "position")
    }
}

用法

import UIKit

class LoginVC: UIViewController
{
    // MARK: Outlets

    @IBOutlet weak var textFieldEmail: UITextField!

    // MARK: View Controller Life Cycle

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    // MARK: Methods

    private func checkEmail() -> Bool
    {
        do
        {
            try textFieldEmail.validatedText(.email)
        }
        catch let error
        {
            let validationError = error as! ValidationError
            // show alert to user with: validationError.localizedDescription
            return false
        }

        return true
    }

    // MARK: Actions

    @IBAction func loginTapped(_ sender: UIButton)
    {
        if checkEmail()
        {
            let email = textFieldEmail.text!
            // move safely ...
        }
    }
}