我想在单个文本字段中检查手机号码和电子邮件ID的验证。我应该如何验证呢?

时间:2019-05-22 05:49:06

标签: swift

我想在单个文本字段中检查“电子邮件ID”和“手机号码”的验证。我应该如何验证同一文本字段的条件?

1 个答案:

答案 0 :(得分:0)

也许这会有所帮助:

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

     extension String {
            var isInt: Bool {
                return Int(self) != nil
            }
        }

        func isValidEmail(testStr: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: testStr)
            }


        if textField.text.characterCount > 6 {
            if textField.text.isInt == true {
              print("this might be users phone number"
            } else if isValidEmail(testStr:textField.text) {
              print("this might be users mail")
            } else {
              print("user entered wrong value or nothing")
        }