有人知道如何在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 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 ...
}
}
}
@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
}
更新答案@Arsonik对Swift 2.2的回答,使用比其他提供的解决方案更少的冗长代码:
extension String {
func isValidEmail() -> Bool {
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: [], range: NSMakeRange(0, self.characters.count)) != nil
}
}
对@和做一个简单的测试。然后发一封确认邮件。
考虑一下:
世界上有一半的人使用非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/