Email & Phone Validation in Swift

后端 未结 21 1829
长发绾君心
长发绾君心 2020-12-07 12:02

i am using the following code for phone number validation. But i am getting the following error. I cant able to proceed further. Help us to take it forward.

         


        
21条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 12:45

    Swift 4.2 and Xcode 10.1

    //For mobile number validation
    func isValidPhone(phone: String) -> Bool {
    
        let phoneRegex = "^((0091)|(\\+91)|0?)[6789]{1}\\d{9}$";
        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
    }
    

    Use like this

    //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")
            }
        }
    }
    

提交回复
热议问题