在Swift中验证电子邮件地址的最佳做法是什么?

ani*_*hin 15 iphone objective-c nspredicate ios swift

我正在寻找最简单,最干净的方法来验证Swift中的电子邮件(String).在Objective-C中我使用了这个方法,但是如果我将它重写为Swift,我在创建谓词时会收到错误"无法解析格式字符串".

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 

    return [emailTest evaluateWithObject:candidate];
}
Run Code Online (Sandbox Code Playgroud)

Cra*_*tis 37

看起来非常简单.如果您在使用Swift转换时遇到问题,那么查看您实际尝试的内容可能会有所帮助.

这对我有用:

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

validateEmail("test@google.com")     // true
validateEmail("invalid@@google.com") // false
Run Code Online (Sandbox Code Playgroud)


Jor*_*uin 6

Swift 3.0版

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

validateEmail("test@google.com")     // true
validateEmail("invalid@@google.com") // false
Run Code Online (Sandbox Code Playgroud)