Swift 中的电子邮件和电话验证

Posted

技术标签:

【中文标题】Swift 中的电子邮件和电话验证【英文标题】:Email & Phone Validation in Swift 【发布时间】:2015-03-15 21:51:34 【问题描述】:

我正在使用以下代码进行电话号码验证。但我收到以下错误。我无法继续进行。帮助我们继续前进。

class PhoneNumberValidation: Validation 
    let PHONE_REGEX = "^\\d3-\\d3-\\d4$"

    func validate(value: String) -> (Bool, ValidationErrorType) 
        if let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) 
            if phoneTest.evaluateWithObject(value) 
                return (true, .NoError)
            
            return (false, .PhoneNumber)
        
        return (false, .PhoneNumber)
    

错误:swift:15:28:条件绑定中的绑定值必须是可选类型

【问题讨论】:

我在您的代码中看不到明显的错误。使用哪个 Xcode 版本?错误发生在哪一行? – 当然最好贴一个不依赖其他类的例子,这样我们就可以直接把你的代码贴到Xcode里面找问题了。 看来您使用的是过时的 Xcode 版本。更新到 Xcode 6.1.1,你的问题就消失了。 【参考方案1】:

是的,您的错误在 XCode 6.1 下方

这个错误是因为if条件必须Bool返回类型,但是在你的if条件返回类型是NSPredicate所以你得到错误swift:条件绑定中的绑定值必须是可选类型的你可以解决如下。

    var phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
         if phoneTest.evaluateWithObject(value) 
                  return (true, .NoError)
             
                 return (false, .PhoneNumber)
            

Swift 中的电子邮件验证。

    func isValidEmail(testStr:String) -> Bool 
            print("validate emilId: \(testStr)")
            let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'|~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'|~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[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])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.)3(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
            let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
            let result = emailTest.evaluateWithObject(testStr)
            return result
         

使用电子邮件验证:

    if isValidEmail("kirit@gmail.com")
            print("Validate EmailID")
        
        else
            print("invalide EmailID")
        

Swift 中的电话号码验证

    func validate(value: String) -> Bool 
            let PHONE_REGEX = "^\\d3-\\d3-\\d4$"
            let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
            let result = phoneTest.evaluate(with: value)
            return result
        

【讨论】:

您使用的是哪个 Xcode 版本?这不能在我的 Xcode 6.1.1 或 6.2beta3 中编译。 – 如果您解释他的代码中的错误,而不是简单地发布您的代码,OP 也会从您的回答中受益更多。 您的回答没有解释为什么 OP 的代码会出现编译器错误。 在“f let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) ------------ 条件绑定中的绑定值附近出现错误是可选类型”... 听起来像 NSPredicate init 函数不返回可选值。谁能证实这一点?如果不是,您不需要(实际上您不能)将该值绑定到 if-let 条件中。 请注意,let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,4" 不适用于大多数长度超过 4 个字符的新自定义 TLD。您可以使用 let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2," 更新它,因此 TLD 没有最大长度限制【参考方案2】:

以下代码适用于 xcode 6.3 beta

func isValidEmail(testStr:String) -> Bool 

   let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,4"
   let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
   let result = range != nil ? true : false
   return result


使用方法:

例如。

if isValidEmail(email.text) == false
//your code here

【讨论】:

或者简单的 !isValidEmail(testStr: email.text) //code here 【参考方案3】:

Swift 3.0 到 5.0 更新解决方案:

//MARK:- Validation Extension-

extension String 

    //To check text field or String is blank or not
    var isBlank: Bool 
        get 
            let trimmed = trimmingCharacters(in: CharacterSet.whitespaces)
            return trimmed.isEmpty
        
    

    //Validate Email

    var isEmail: Bool 
        do 
            let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,", options: .caseInsensitive)
            return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) != nil
         catch 
            return false
        
    

    var isAlphanumeric: Bool 
        return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
    

    //validate Password
    var isValidPassword: Bool 
        do 
            let regex = try NSRegularExpression(pattern: "^[a-zA-Z_0-9\\-_,;.:#+*?=!§$%&/()@]+$", options: .caseInsensitive)
            if(regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil)

                if(self.characters.count>=6 && self.count<=20)
                    return true
                else
                    return false
                
            else
                return false
            
         catch 
            return false
        
    

使用电子邮件验证:

if(txtEmail.isEmail)

Swift 2.0 解决方案

将这些行粘贴到代码中的任何位置。(或在您的常量文件中)

extension String 

    //To check text field or String is blank or not
    var isBlank: Bool 
        get 
            let trimmed = stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
            return trimmed.isEmpty
        
    

    //Validate Email
    var isEmail: Bool 
        do 
            let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,", options: .CaseInsensitive)
            return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) != nil
         catch 
            return false
        
    

    //validate PhoneNumber
    var isPhoneNumber: Bool 

        let charcter  = NSCharacterSet(charactersInString: "+0123456789").invertedSet
        var filtered:NSString!
        let inputString:NSArray = self.componentsSeparatedByCharactersInSet(charcter)
        filtered = inputString.componentsJoinedByString("")
        return  self == filtered

    

【讨论】:

这是不正确的。因为它接受像 "!sd@gh" 这样的字符串作为正确的电子邮件地址。 您可以在一行中重写最后一次电话检查,而无需拆分和加入return self.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "+0123456789").invertedSet) == nil @AbbasAngouti 请改进我同意这个问题的答案。我也会检查我的空闲时间。 @AbbasAngouti 我改进了电子邮件验证正则表达式,请检查。 还是不正确,如果你输入 "!sd@gh.com" 它返回 true【参考方案4】:

File-New-File.Make 一个名为 AppExtension 的 Swift 类。添加以下内容。

        extension UIViewController
            func validateEmailAndGetBoolValue(candidate: String) -> Bool 
                let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,6"
                return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(candidate)
            
        

        Use: 
        var emailValidator:Bool?
        self.emailValidator =  self.validateEmailAndGetBoolValue(resetEmail!)
                        print("emailValidator : "+String(self.emailValidator?.boolValue))

        Use a loop to alternate desired results.


    OR
        extension String
        
        //Validate Email
            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
                

            
        

        Use:
        if(resetEmail!.isEmail)
                        
                        AppController().requestResetPassword(resetEmail!)
                        self.view.makeToast(message: "Sending OTP")
                        
                        else
                        
                            self.view.makeToast(message: "Please enter a valid email")
                        

【讨论】:

【参考方案5】:

为了多样化的另一种解决方案..

public extension String 
    public var validPhoneNumber:Bool 
        let types:NSTextCheckingType = [.PhoneNumber]
        guard let detector = try? NSDataDetector(types: types.rawValue) else  return false 

        if let match = detector.matchesInString(self, options: [], range: NSMakeRange(0, characters.count)).first?.phoneNumber 
            return match == self
        else
            return false
        
    


//and use like so:
if "16465551212".validPhoneNumber 
    print("valid phone number")

【讨论】:

validPhoneNumber 的结果将始终返回“true”。它只是创建一个 phoneNumber 类型的 NSTextCheckingResult,所以比较总是正确的。我认为您打算尝试使用 NSDataDetector。 谢谢@EPage_Ed,你是 100% 正确的!我已经更新以反映预期的实现。谢谢!【参考方案6】:

也许是 Swift 2 中更好的手机验证器:

extension String 
    var isPhoneNumber: Bool 
        do 
            let detector = try NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue)
            let matches = detector.matchesInString(self, options: [], range: NSMakeRange(0, self.characters.count))
            if let res = matches.first 
                return res.resultType == .PhoneNumber && res.range.location == 0 && res.range.length == self.characters.count
             else 
                return false
            
         catch 
            return false
        
    

【讨论】:

对于 Swift 4.2 var isPhoneNumber: Bool do 让检测器 = 尝试 NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue) 让匹配 = 检测器.matches(in: self, options: [], range: NSMakeRange(0, self.count)) if let res = matches.first return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.count else 返回错误 捕捉 返回错误 Swift 5 var isValidPhone : Bool do 让检测器 = 尝试 NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue) 让匹配 = 检测器.matches(in: self, options: [], range : NSMakeRange(0, self.count)) if let res = matches.first return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.count else return错误 捕捉 返回错误 【参考方案7】:

斯威夫特 3:

private func validate(phoneNumber: String) -> Bool 
    let charcterSet  = NSCharacterSet(charactersIn: "+0123456789").inverted
    let inputString = phoneNumber.components(separatedBy: charcterSet)
    let filtered = inputString.joined(separator: "")
    return  phoneNumber == filtered

【讨论】:

这只是验证您拥有所有数字而不是有效的电话号码【参考方案8】:

Kirit Modi 关于 Swift 3 电子邮件验证的回应:

func isValidEmail(testStr:String) -> Bool 
    let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'|~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'|~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[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])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.)3(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    let result = emailTest.evaluate(with: testStr)
    return result
  

【讨论】:

【参考方案9】:

电话正则表达式仅适用于 ّIran 电话号码

func isValidPhone(phone: String) -> Bool 

        let PHONE_REGEX = "^09[0-9'@s]9,9$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
        let result =  phoneTest.evaluate(with: phone)
        return result

    

【讨论】:

【参考方案10】:

为 Swift 3 更新

extension String 
    var isPhoneNumber: Bool 
        do 
            let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
            let matches = detector.matches(in: self, options: [], range: NSMakeRange(0, self.characters.count))
            if let res = matches.first 
                return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.characters.count
             else 
                return false
            
         catch 
            return false
        
    

【讨论】:

【参考方案11】:

您可以创建单独的类进行验证,如下所示:

enum AIValidationRule: Int 
case
EmptyCheck,
MinMaxLength,
FixedLength,
EmailCheck,
UpperCase,
LowerCase,
SpecialCharacter,
DigitCheck,
WhiteSpaces,
None

let ValidationManager = AIValidationManager.sharedManager


func validateTextField(txtField:AITextField, forRule rule:AIValidationRule, withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? 

    switch rule 

    case .EmptyCheck:
        return (txtField.text?.characters.count == 0) ? (false,"Please enter \(txtField.placeholder!.lowercased())",txtField) : nil


    case .MinMaxLength:
        return (txtField.text!.characters.count < minChar || txtField.text!.characters.count > maxChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) to \(maxChar) characters",txtField) : nil

    case .FixedLength:
        return (txtField.text!.characters.count != minChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) characters",txtField) : nil


    case .EmailCheck:
        return (!(txtField.text?.isValidEmail())!) ? (false,"Please enter valid email",txtField) : nil


    case .UpperCase:
        return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.uppercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one uppercase letter",txtField) : nil


    case .LowerCase:
        return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.lowercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one lowercase letter",txtField) : nil


    case .SpecialCharacter:
        let symbolCharacterSet = NSMutableCharacterSet.symbol()
        symbolCharacterSet.formUnion(with: NSCharacterSet.punctuationCharacters)
        return ((txtField.text! as NSString).rangeOfCharacter(from: symbolCharacterSet as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one special letter",txtField) : nil


    case .DigitCheck:
        return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet(charactersIn: "0123456789") as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one digit letter",txtField) : nil

    case .WhiteSpaces:
        return (txtField.text!.containsAdjacentSpaces() || txtField.text!.isLastCharcterAWhiteSpace()) ? (false,"\(txtField.placeholder!) seems to be invalid",txtField) : nil

    case .None:
        return nil
    


    func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule]) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? 
    return validateTextField(txtField: txtField, forRules: rules, withMinimumChar: 0, andMaximumChar: 0)




func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule], withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? 

    var strMessage:String = ""
    for eachRule in rules 

        if let result = validateTextField(txtField: txtField, forRule: eachRule, withMinimumChar: minChar, andMaximumChar: maxChar) 
            if(eachRule == AIValidationRule.EmptyCheck)
                return result
            else
                strMessage += "\(strMessage.characters.count == 0 ? "" : "\n\n") \(result.errMessage)"
            
        
    
    return strMessage.characters.count > 0 ? (false,strMessage,txtField) : nil

【讨论】:

【参考方案12】:

使用 Swift 3

 func validate(value: String) -> Bool 
    let PHONE_REGEX = "^\\d3-\\d3-\\d4$"
    let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
    let result =  phoneTest.evaluate(with: value)
    return result

【讨论】:

【参考方案13】:

斯威夫特 3 验证电子邮件

class func validateEmail(email: String) -> Bool

    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,6"

    return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)


电话号码验证

class func validatePhoneNumber(value: String) -> Bool 

    let PHONE_REGEX = "^\\d3-\\d3-\\d4$"
    let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
    let result =  phoneTest.evaluate(with: value)
    return result

【讨论】:

一个非常好的电话号码被拒绝了。【参考方案14】:

适用于 Swift 3.0 及更高版本

var isPhoneNumber: Bool
let allowedCharacters = CharacterSet(charactersIn: "+0123456789").inverted
let inputString = components(separatedBy: allowedCharacters)
let filtered = inputString.joined(separator: "")
return self == filtered

【讨论】:

什么是components【参考方案15】:

为 Swift 更新:

以下代码用于电子邮件、姓名、手机和密码验证;

// Name validation
func isValidName(_ nameString: String) -> Bool 

    var returnValue = true
    let mobileRegEx =  "[A-Za-z]2"  // "^[A-Z0-9a-z.-_]5$"

    do 
        let regex = try NSRegularExpression(pattern: mobileRegEx)
        let nsString = nameString as NSString
        let results = regex.matches(in: nameString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        
            returnValue = false
        

     catch let error as NSError 
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    

    return  returnValue


// password validation
func isValidPassword(_ PasswordString: String) -> Bool 

    var returnValue = true
    let mobileRegEx =  "[A-Za-z0-9.-_@#$!%&*]5,15$"  // "^[A-Z0-9a-z.-_]5$"

    do 
        let regex = try NSRegularExpression(pattern: mobileRegEx)
        let nsString = PasswordString as NSString
        let results = regex.matches(in: PasswordString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        
            returnValue = false
        

     catch let error as NSError 
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    

    return  returnValue


// email validaton
func isValidEmailAddress(_ emailAddressString: String) -> Bool 

    var returnValue = true
    let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,3"

    do 
        let regex = try NSRegularExpression(pattern: emailRegEx)
        let nsString = emailAddressString as NSString
        let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        
            returnValue = false
        

     catch let error as NSError 
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    

    return  returnValue


// mobile no. validation
func isValidPhoneNumber(_ phoneNumberString: String) -> Bool 

    var returnValue = true
    //        let mobileRegEx = "^[789][0-9]9,11$"
    let mobileRegEx = "^[0-9]10$"

    do 
        let regex = try NSRegularExpression(pattern: mobileRegEx)
        let nsString = phoneNumberString as NSString
        let results = regex.matches(in: phoneNumberString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        
            returnValue = false
        

     catch let error as NSError 
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    

    return  returnValue

//如何使用?

let isFullNameValid = isValidName("ray")

if isFullNameValid
    print("Valid name...")
else
    print("Invalid name...")

【讨论】:

【参考方案16】:

斯威夫特 4.1。

func isValidPhone(phone: String) -> Bool 

      let phoneRegex = "^[0-9]6,14$";
      let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
      return valid
   

func isValidEmail(candidate: String) -> Bool 

       let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,"
       var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)
        if valid 
            valid = !candidate.contains("..")
        
        return valid
  

【讨论】:

【参考方案17】:

Swift 4.2 和 Xcode 10.1

//For mobile number validation
func isValidPhone(phone: String) -> Bool 

    let phoneRegex = "^((0091)|(\\+91)|0?)[6789]1\\d9$";
    let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
    return valid


//For email validation
func isValidEmail(candidate: 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: candidate)
    if valid 
        valid = !candidate.contains("..")
    
    return valid

这样使用

//Button Action
@IBAction func onClickRegrBtn(_ sender: UIButton) 
    //Check net connection here
    let networkReachability = Reachability.forInternetConnection()
    let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
    if networkStatus == NotReachable.rawValue 
        let msg = SharedClass.sharedInstance.noNetMsg
        SharedClass.sharedInstance.alert(view: self, title: "", message: msg)//Display alert message
     else 

        let mobileTrimmedString = mobileNoTF.text?.trimmingCharacters(in: .whitespaces) //Trim white spaces

        if mobileTrimmedString != "" 
            if isValidPhone(phone: mobileTrimmedString!) == false 
                SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter valid mobile number")
             else 
                UserDefaults.standard.set(mobileTrimmedString, forKey: "mobile") //setObject
                sendMobileNumber()//Call function...
            

         else 
            mobileNoTF.text = ""
            //Call alert function
            SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter mobile number")
        
    

【讨论】:

【参考方案18】:

Swift 4+

您可以使用简化的regex "^[6-9]\\d9$"

^     #Match the beginning of the string
[6-9] #Match a 6, 7, 8 or 9
\\d   #Match a digit (0-9 and anything else that is a "digit" in the regex engine)
9   #Repeat the previous "\d" 9 times (9 digits)
$     #Match the end of the string

From Reference

印度 10 位移动验证(可以以 6、7、8、9 开头)-

extension String 
    var isValidContact: Bool 
        let phoneNumberRegex = "^[6-9]\\d9$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneNumberRegex)
        let isValidPhone = phoneTest.evaluate(with: self)
        return isValidPhone
    
 

用法:-

print("9292929292".isValidContact)//true
print("5454545454".isValidContact)//false

邮箱验证可以查看this

【讨论】:

电话号码验证不起作用我尝试使用“7982391667” @DilipTiwari print("7982391667".isValidContact) returns true 工作正常 不,兄弟它不工作,你能分享你如何使用文本字段【参考方案19】:

“验证电子邮件”-Swift 4 的解决方案: 创建这个类:

import Foundation

public class EmailAddressValidator 
    public init() 
    

    public func validateEmailAddress(_ email: String) -> Bool 
        let emailTest = NSPredicate(format: "SELF MATCHES %@", String.emailValidationRegEx)

        return emailTest.evaluate(with: email)
    


private extension String 
    static let emailValidationRegEx = "(?:[\\pL0-9!#$%\\&'*+/=?\\^_`|~-]+(?:\\.[\\pL0-9!#$%\\&'*+/=?\\^_`|" +
        "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" +
        "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\pL0-9](?:[a-" +
        "z0-9-]*[\\pL0-9])?\\.)+[\\pL0-9](?:[\\pL0-9-]*[\\pL0-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]?|[\\pL0-9-]*[\\pL0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" +
    "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"

并像这样使用它:

let validator = EmailAddressValidator()
let isValid = validator.validateEmailAddress("testmail@testmail.com")

【讨论】:

【参考方案20】:

斯威夫特 4 和斯威夫特 5:

func isValidPhone(phone: String) -> Bool 
        let phoneRegex = "^[0-9+]0,1+[0-9]5,16$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluate(with: phone)
    

func isValidEmail(email: String) -> Bool 
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]2,64"
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: email)
    

+1994423565 - 有效 ++1994423565 - 无效 01994423565 - 有效 001994423565 - 有效 something@example.com - 有效 something@.com - 无效

【讨论】:

123456 是一个有效数字。为什么? @Hemang 这很简单,因为在正则表达式中为数字,这个“^[0-9+]0,1”部分是 ^ - 仅检查字符串开始 [0-9+] - 字符我们是允许的(所以允许所有数字和 + 号)0,1 - 我们正在寻找的允许字符数,所以它可以为零,所以加号不是必需的......实际上我什至会更新这个答案通过电话的下一个正则表达式: "^[+]?+[0-9]5,16$" 所以我们只检查字符串开头是否有加号,?这里与 0,1 相同【参考方案21】:

iksnae 很棒的答案的更新版本。它不是正则表达式,但我认为它是验证所有国家/地区电话号码的最佳解决方案,因为它足够聪明地知道该国家/地区的电话分机代码是否有效

extension String 
    public var validPhoneNumber: Bool 
        let types: NSTextCheckingResult.CheckingType = [.phoneNumber]
        guard let detector = try? NSDataDetector(types: types.rawValue) else  return false 
        if let match = detector.matches(in: self, options: [], range: NSMakeRange(0, self.count)).first?.phoneNumber 
            return match == self
         else 
            return false
        
    


print("\("+96 (123) 456-0990".validPhoneNumber)") //returns false, smart enough to know if country phone code is valid as well ?
print("\("+994 (123) 456-0990".validPhoneNumber)") //returns true because +994 country code is an actual country phone code
print("\("(123) 456-0990".validPhoneNumber)") //returns true
print("\("123-456-0990".validPhoneNumber)") //returns true
print("\("1234560990".validPhoneNumber)") //returns true

【讨论】:

嗨,哪个输入不准确? NSDataDetector 在电话号码方面不准确,大多数情况下它会为无效号码返回 true 感谢指正。那么你认为哪一个是最好的答案呢? ?

以上是关于Swift 中的电子邮件和电话验证的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift 4 中更新 Firebase 身份验证中的电子邮件地址

在firebase中实现电话和电子邮件身份验证的最佳方法是一次性使用?

Swift 中的 XLForm 验证

如何通过vee-validate同时验证电子邮件和电话

在 Angular 7 表单控件的单个输入字段中验证电子邮件、电话和 PAN 号码

php正则表达式验证(邮件地址Url地址电话号码邮政编码)