查看有效的电话号码

时间:2016-04-22 09:22:27

标签: ios swift

我有一个文本字段用于输入电话号码,用户必须按OK按钮。

然后我写了一些函数来检查输入的数字是有效数字还是10位数字。我不想添加国家/地区代码。我已分开了。

但是当我按下OK按钮时,它会给我uialert - 包括我自己号码在内的所有号码的错号码。我不知道我错过的任何代码?

    func validate(value: String) -> Bool {
        let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
        var phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
        var result =  phoneTest.evaluateWithObject(value)
        return result
    }

    @IBAction func confirmAction(sender: AnyObject) {

        if validate(phoneNumber.text!)
        {
            print("Validate EmailID")
            let phone = countryCode.text! + phoneNumber.text!
            UserNetworkInterface().generateSms(phone, onCompletion: nil)
            performSegueWithIdentifier("ConfirmSmsCode", sender: self)
        }
        else
        {
            print("invalide EmailID")
            let alert = UIAlertView()
            alert.title = "Message"
            alert.message = "Enter Valid Contact Number"
            alert.addButtonWithTitle("Ok")
            alert.delegate = self
            alert.show()
        }
  }

更新:

 @IBAction func confirmAction(sender: AnyObject) {

        if let phoneNumberValidator = phoneNumber.isPhoneNumber
        {
            print("Validate EmailID")
            let phone = countryCode.text! + phoneNumber.text!
            UserNetworkInterface().generateSms(phone, onCompletion: nil)
            performSegueWithIdentifier("ConfirmSmsCode", sender: self)


        }
        else
        {
            print("invalide EmailID")
            let alert = UIAlertView()
            alert.title = "Message"
            alert.message = "Enter Valid Contact Number"
            alert.addButtonWithTitle("Ok")
            alert.delegate = self
            alert.show()
            phoneNumber.text = ""


        }
                    // Number valid


  }

6 个答案:

答案 0 :(得分:17)

试试这个。

对String进行扩展。

Swift 4

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.count))
            if let res = matches.first {
                return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.count
            } else {
                return false
            }
        } catch {
            return false
        }
    }
}

较旧的Swift版本

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
        }
    }
}

用法:

override func viewWillAppear(animated: Bool) {

//Sample check
let phoneString = "8888888888"

let phoneNumberValidator = phoneString.isPhoneNumber
print(phoneNumberValidator)

}

答案 1 :(得分:1)

Swift 3

对于那些希望phone number to have a minimum of 10 characters使用以下代码的人(修改后的@Alvin George代码)

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 && self.characters.count == 10
            } else {
                return false
            }
        } catch {
            return false
        }
    }
} 

用法

ooverride func viewDidLoad() {
    super.viewDidLoad()

    //Example
    let phoneNumberString = "8500969696"

    let phoneNumberValidation = phoneNumberString.isPhoneNumber
    print(phoneNumberValidation) 
    // Prints: true

}

答案 2 :(得分:1)

尝试此操作以验证印度10位手机号码

var isValidMobileNo: Bool {
    let PHONE_REGEX = "^[7-9][0-9]{9}$";
    let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
    let result =  phoneTest.evaluate(with: self)
    return result
}

答案 3 :(得分:0)

为Swift 4修改的@Alvin George代码,该代码也仅接受10位电话号码:

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.count))
            if let res = matches.first {
                return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.count && self.count == 10
            } else {
                return false
            }
        } catch {
            return false
        }
    }
} 

答案 4 :(得分:0)

轻松验证印度10位数手机号码

func isValidPhone(testStr:String) -> Bool {
    let phoneRegEx = "^[6-9]\\d{9}$"
    var phoneNumber = NSPredicate(format:"SELF MATCHES %@", phoneRegEx)
    return phoneNumber.evaluate(with: testStr)
}

答案 5 :(得分:-1)

修改@AG的答案以更新到Swift 5:

extension String {
    func isValidPhone() -> Bool {
        do {
            let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
            let matches = detector.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 false
            }
        } catch {
            return false
        }
    }
}