有人知道如何在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;
}
}
但我无法翻译成斯威夫特。
我建议使用它作为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 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上都能成功编译。