有人知道如何在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;
}
}
但我无法翻译成斯威夫特。
斯威夫特5
func isValidEmailAddress(emailAddressString: String) -> Bool {
var returnValue = true
let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"
do {
let regex = try NSRegularExpression(pattern: emailRegEx)
let nsString = emailAddressString as NSString
let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
然后:
let validEmail = isValidEmailAddress(emailAddressString: "your@email.com")
print(validEmail)
对于那些还在寻找答案的人,请看看下面的框架;
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)
请在链接处查看自述文件以获取更多用例。
我唯一添加到响应列表的是,对于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上都能成功编译。
@JeffersonBe的答案是接近的,但如果字符串是“包含someone@something.com一个有效的电子邮件”,这不是我们想要的。下面是String上的一个扩展,它工作得很好(并且允许测试有效的phoneNumber和其他数据检测器来引导。
/// Helper for various data detector matches.
/// Returns `true` iff the `String` matches the data detector type for the complete string.
func matchesDataDetector(type: NSTextCheckingResult.CheckingType, scheme: String? = nil) -> Bool {
let dataDetector = try? NSDataDetector(types: type.rawValue)
guard let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length)) else {
return false
}
return firstMatch.range.location != NSNotFound
// make sure the entire string is an email, not just contains an email
&& firstMatch.range.location == 0
&& firstMatch.range.length == length
// make sure the link type matches if link scheme
&& (type != .link || scheme == nil || firstMatch.url?.scheme == scheme)
}
/// `true` iff the `String` is an email address in the proper form.
var isEmail: Bool {
return matchesDataDetector(type: .link, scheme: "mailto")
}
/// `true` iff the `String` is a phone number in the proper form.
var isPhoneNumber: Bool {
return matchesDataDetector(type: .phoneNumber)
}
/// number of characters in the `String` (required for above).
var length: Int {
return self.characters.count
}
这是@Fattie的“THE REASONABLE SOLUTION”的新版本,在Swift 4.1的一个名为String+Email.swift的新文件中测试:
import Foundation
extension String {
private static let __firstpart = "[A-Z0-9a-z]([A-Z0-9a-z._%+-]{0,30}[A-Z0-9a-z])?"
private static let __serverpart = "([A-Z0-9a-z]([A-Z0-9a-z-]{0,30}[A-Z0-9a-z])?\\.){1,5}"
private static let __emailRegex = __firstpart + "@" + __serverpart + "[A-Za-z]{2,6}"
public var isEmail: Bool {
let predicate = NSPredicate(format: "SELF MATCHES %@", type(of:self).__emailRegex)
return predicate.evaluate(with: self)
}
}
所以它的用法很简单:
let str = "mail@domain.com"
if str.isEmail {
print("\(str) is a valid e-mail address")
} else {
print("\(str) is not a valid e-mail address")
}
我只是不喜欢向String对象添加func,因为作为电子邮件地址是它们固有的(或不是)。根据我的理解,Bool属性比func更适合。