有人知道如何在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 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
}
}
}
对于那些还在寻找答案的人,请看看下面的框架;
ATGvalidator
它是一个基于规则的验证框架,可以处理大部分开箱即用的验证。最重要的是,它有表单验证器,支持同时验证多个文本字段。
要验证电子邮件字符串,请使用以下方法;
"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)
请在链接处查看自述文件以获取更多用例。
在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())