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

但我无法翻译成斯威夫特。


当前回答

我更喜欢用扩展名。此外,这个url http://emailregex.com可以帮助您测试regex是否正确。事实上,该站点为某些编程语言提供了不同的实现。我分享了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)
    }
}

其他回答

我喜欢扩展

   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.

}

我建议使用它作为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")
}

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

在Swift 5.7中,在Regex类的帮助下,我们可以以简单有效的方式验证电子邮件地址

private func isValidEmail(_ email: String) -> Bool {
      guard let emailRegex = try? Regex("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}")  
      else { return false }
      return email.firstMatch(of: emailRegex) != nil
   }

我们还可以使用属性包装器来提高效率:

@propertyWrapper
struct EmailPropertyWrapper {
  private var _value: String
  var wrappedValue: String {
    get { return isValidEmail(_value) ? _value : String() }
    set { _value = newValue }
  }
  
  init(email: String) {
    _value = email
  }

  private func isValidEmail(_ email: String) -> Bool {
      guard let emailRegex = try? Regex("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}")  
      else { return false }
      return email.firstMatch(of: emailRegex) != nil
   }
}

struct User {
  var name: String
  @EmailPropertyWrapper var email: String
  
  func validateProperty() -> Bool {
    if name.isEmpty || email.isEmpty { return false }
    return true
  }
}

let user = User(name: "Sy", email: .init(email: "wwdc@icloud.com"))

print(user.validateProperty())

我唯一添加到响应列表的是,对于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和Ubuntu上都能成功编译。