有人知道如何在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;
}
}
但我无法翻译成斯威夫特。
这是Swift 2.0 - 2.2的更新版本
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
} catch {
return false
}
}
我唯一添加到响应列表的是,对于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上都能成功编译。
Swift 5 -可伸缩的验证层
使用此层,您将轻松地在任何文本字段上获得惊人的验证。
只需遵循以下流程即可。
1. 添加这些枚举:
import Foundation
enum ValidatorType
{
case email
case name
// add more cases ...
}
enum ValidationError: Error, LocalizedError
{
case invalidUserName
case invalidEmail
// add more cases ...
var localizedDescription: String
{
switch self
{
case .invalidEmail:
return "Please kindly write a valid email"
case .invalidUserName:
return "Please kindly write a valid user name"
}
}
}
2. 将此功能添加到String:
extension String
{
// MARK:- Properties
var isValidEmail: Bool
{
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: self)
}
// MARK:- Methods
func validatedText(_ validationType: ValidatorType) throws
{
switch validationType
{
case .name:
try validateUsername()
case .email:
try validateEmail()
}
}
// MARK:- Private Methods
private func validateUsername() throws
{
if isEmpty
{
throw ValidationError.invalidUserName
}
}
private func validateEmail() throws
{
if !isValidEmail
{
throw ValidationError.invalidEmail
}
// add more validations if you want like empty email
}
}
3.添加以下功能到UITextField:
import UIKit
extension UITextField
{
func validatedText(_ validationType: ValidatorType) throws
{
do
{
try text?.validatedText(validationType)
}
catch let validationError
{
shake()
throw validationError
}
}
// MARK:- Private Methods
private func shake()
{
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.1
animation.repeatCount = 5
animation.fromValue = NSValue(cgPoint: CGPoint(x: center.x + 6, y: center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: center.x - 6, y: center.y))
layer.add(animation, forKey: "position")
}
}
使用
import UIKit
class LoginVC: UIViewController
{
// MARK: Outlets
@IBOutlet weak var textFieldEmail: UITextField!
// MARK: View Controller Life Cycle
override func viewDidLoad()
{
super.viewDidLoad()
}
// MARK: Methods
private func checkEmail() -> Bool
{
do
{
try textFieldEmail.validatedText(.email)
}
catch let error
{
let validationError = error as! ValidationError
// show alert to user with: validationError.localizedDescription
return false
}
return true
}
// MARK: Actions
@IBAction func loginTapped(_ sender: UIButton)
{
if checkEmail()
{
let email = textFieldEmail.text!
// move safely ...
}
}
}
创建简单的扩展:
extension NSRegularExpression {
convenience init(pattern: String) {
try! self.init(pattern: pattern, options: [])
}
}
extension String {
var isValidEmail: Bool {
return isMatching(expression: NSRegularExpression(pattern: "^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$"))
}
//MARK: - Private
private func isMatching(expression: NSRegularExpression) -> Bool {
return expression.numberOfMatches(in: self, range: NSRange(location: 0, length: characters.count)) > 0
}
}
例子:
"b@bb.pl".isValidEmail //true
"b@bb".isValidEmail //false
你可以扩展以下扩展到任何你需要的:isValidPhoneNumber, isValidPassword等…
在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
}