这是本地处理电子邮件验证的好方法:
Handling email validation using built-in functionality
我也有这种方式用正则表达式来处理它:
这是来自I Knew How To Validate An Email Address Until I Read The RFC的正则表达式
import Foundation
let pattern = "^(?!\\.)(\"([^\"\\r\\\\]|\\\\[\"\\r\\\\])*\"|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\\.)\\.)*)(?<!\\.)@[a-z0-9][\\w\\.-]*[a-z0-9]\\.[a-z][a-z\\.]*[a-z]$"
let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)
// tests in the format (email, isValid)
let tests = [
("NotAnEmail", false),
("@NotAnEmail", false),
("\"test\\\rblah\"@example.com", true),
("\"test\rblah\"@example.com", false),
("\"test\\\"blah\"@example.com", true),
("\"test\"blah\"@example.com", false),
("customer/department@example.com", true),
("$A12345@example.com", true),
("!def!xyz%abc@example.com", true),
("_Yosemite.Sam@example.com", true),
("~@example.com", true),
(".wooly@example.com", false),
("wo..oly@example.com", false),
("pootietang.@example.com", false),
(".@example.com", false),
("\"Austin@Powers\"@example.com", true),
("Ima.Fool@example.com", true),
("\"Ima.Fool\"@example.com", true),
("\"Ima Fool\"@example.com", true),
("Ima Fool@example.com", false)]
for (index,(email,isValid)) in tests.enumerate() {
let eval = predicate.evaluateWithObject(email)
if eval == isValid {
print(index, ": VALID!")
}
}
输出:
0 : VALID!
1 : VALID!
2 : VALID!
3 : VALID!
4 : VALID!
5 : VALID!
6 : VALID!
8 : VALID!
10 : VALID!
11 : VALID!
12 : VALID!
13 : VALID!
14 : VALID!
15 : VALID!
17 : VALID!
18 : VALID!
19 : VALID!