有人知道如何在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;
}
}
但我无法翻译成斯威夫特。
或者你可以扩展可选文本UITextField:
使用方法:
if emailTextField.text.isEmailValid() {
print("email is valid")
}else{
print("wrong email address")
}
扩展:
extension Optional where Wrapped == String {
func isEmailValid() -> Bool{
guard let email = self else { return false }
let emailPattern = "[A-Za-z-0-9.-_]+@[A-Za-z0-9]+\\.[A-Za-z]{2,3}"
do{
let regex = try NSRegularExpression(pattern: emailPattern, options: .caseInsensitive)
let foundPatters = regex.numberOfMatches(in: email, options: .anchored, range: NSRange(location: 0, length: email.count))
if foundPatters > 0 {
return true
}
}catch{
//error
}
return false
}
}
这里有很多正确答案,但许多“正则表达式”是不完整的,可能会发生像“name@domain”这样的电子邮件结果是有效的电子邮件,但它不是。这里是完整的解决方案:
extension String {
var isEmailValid: Bool {
do {
let regex = try NSRegularExpression(pattern: "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", options: .CaseInsensitive)
return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
} catch {
return false
}
}
}
对@和做一个简单的测试。然后发一封确认邮件。
考虑一下:
世界上有一半的人使用非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/
在Swift 4.2和Xcode 10.1中
//Email validation
func isValidEmail(email: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
if valid {
valid = !email.contains("Invalid email id")
}
return valid
}
//Use like this....
let emailTrimmedString = emailTF.text?.trimmingCharacters(in: .whitespaces)
if isValidEmail(email: emailTrimmedString!) == false {
SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter valid email")
}
如果你想使用SharedClass。
//This is SharedClass
import UIKit
class SharedClass: NSObject {
static let sharedInstance = SharedClass()
//Email validation
func isValidEmail(email: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
if valid {
valid = !email.contains("Invalid email id")
}
return valid
}
private override init() {
}
}
并调用这样的函数....
if SharedClass.sharedInstance. isValidEmail(email: emailTrimmedString!) == false {
SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter correct email")
//Your code here
} else {
//Code here
}