Email & Phone Validation in Swift

后端 未结 21 1775
长发绾君心
长发绾君心 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:48

    Updated version of iksnae's awesome answer. It's not a regex, but I think it's the best solution to validate all countries' phone numbers as it is smart enough to know if the country's phone extension code is valid as well.

    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 

提交回复
热议问题