有人知道如何在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;
}
}
但我无法翻译成斯威夫特。
我改进了@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)
作为String类扩展
斯威夫特4
extension String {
func isValidEmail() -> Bool {
// here, `try!` will always succeed because the pattern is valid
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.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
}
使用
if "rdfsdsfsdfsd".isValidEmail() {
}
如果你正在寻找一个干净简单的解决方案,你应该看看https://github.com/nsagora/validation-components。
它包含一个电子邮件验证谓词,很容易集成在你的代码:
let email = "test@example.com"
let rule = EmailValidationPredicate()
let isValidEmail = rule.evaluate(with: email)
在引擎盖后面,它使用RFC 5322 regex (http://emailregex.com):
let regex = "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" +
"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" +
"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" +
"z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-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]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" +
"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
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 ...
}
}
}