有人知道如何在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;
}
}
但我无法翻译成斯威夫特。
我会使用npredicate:
func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
对于Swift 3.0之前的版本:
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
对于Swift 1.2之前的版本:
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {
return emailPred.evaluateWithObject(email)
}
return false
}
以上大多数正则表达式示例在电子邮件存在基本问题时都无法捕获错误。例如
h..1@nyu.edu -连续的点
ab1234@.nyu.edu - @后面的点
a.bcdnle12.@email.com - @前的点
.abc@email.com -以一个点开始
这是一个字符串扩展,我使用了更严格的规则使用正则表达式。
extension String {
func isValidEmail() -> Bool {
let emailRegEx = "^(?!\\.)([A-Z0-9a-z_%+-]?[\\.]?[A-Z0-9a-z_%+-])+@[A-Za-z0-9-]{1,20}(\\.[A-Za-z0-9]{1,15}){0,10}\\.[A-Za-z]{2,20}$"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: self)
}
}
下面是我们如何为它编写测试用例。
XCTAssertFalse("ab1234@.nyu.edu".isValidEmail())
XCTAssertTrue("valid_email@email.com".isValidEmail())
对@和做一个简单的测试。然后发一封确认邮件。
考虑一下:
世界上有一半的人使用非ascii字符。
正则表达式是缓慢和复杂的。顺便说一下,至少检查字符/字母/Unicode范围,而不是az。
因为RFC规则和相应的正则表达式太复杂,所以无法进行完全验证。
我用的是这个基本的检查:
// similar to https://softwareengineering.stackexchange.com/a/78372/22077
import Foundation
/**
Checks that
- length is 254 or less (see https://stackoverflow.com/a/574698/412916)
- there is a @ which is not the first character
- there is a . after the @
- there are at least 4 characters after the @
*/
func isValidEmail(email: String) -> Bool {
guard email.count <= 254 else {
return false
}
let pos = email.lastIndex(of: "@") ?? email.endIndex
return (pos != email.startIndex)
&& ((email.lastIndex(of: ".") ?? email.startIndex) > pos)
&& (email[pos...].count > 4)
}
print(isValidEmail(email: "アシッシュ@ビジネス.コム")) // true
请注意,
它比regex和NSDataDetector快得多。
它正确地报告以下内容为有效:
Håkan.Söderström@malmö.se"
punnycode@XN--0ZWM56D.XN--HGBK6AJ7F53BBA"
试@例子.测试.مثال.آزمایشی"
foo.bar+something@blah.com"
m@foo.co.uk
它错误地将以下内容报告为无效——因为它们实际上是有效的,但可能是用户错误的产物:
a @ b
a@b
相关:
电子邮件地址验证应该走多远?
在线电子邮件检查:https://isemail.info/
我改进了@Azik的答案。我允许使用准则允许的更多特殊字符,并返回一些无效的额外边缘情况。
小组认为这里只允许本地部分的。_%+-是不正确的。参见@Anton Gogolev对这个问题的回答或参见下文:
The local-part of the email address may use any of these ASCII
characters:
uppercase and lowercase Latin letters A to Z and a to z;
digits 0 to 9;
special characters !#$%&'*+-/=?^_`{|}~;
dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g.
John..Doe@example.com is not allowed but "John..Doe"@example.com is
allowed);
space and "(),:;<>@[\] characters are allowed with
restrictions (they are only allowed inside a quoted string, as
described in the paragraph below, and in addition, a backslash or
double-quote must be preceded by a backslash);
comments are allowed
with parentheses at either end of the local-part; e.g.
john.smith(comment)@example.com and (comment)john.smith@example.com
are both equivalent to john.smith@example.com;
我使用的代码将不允许限制性的特殊字符,但将允许比这里的大多数答案更多的选项。我更喜欢更宽松的验证,而不是谨慎的错误。
if enteredText.contains("..") || enteredText.contains("@@")
|| enteredText.hasPrefix(".") || enteredText.hasSuffix(".con"){
return false
}
let emailFormat = "[A-Z0-9a-z.!#$%&'*+-/=?^_`{|}~]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
return emailPredicate.evaluate(with: enteredText)