gpt4 book ai didi

ios - 检查有效的电话号码

转载 作者:搜寻专家 更新时间:2023-10-31 21:50:02 24 4
gpt4 key购买 nike

我有一个用于输入电话号码的文本字段,用户必须按 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


}

最佳答案

试试这个。

对字符串进行扩展。

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: NSRange(location: 0, length: 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)

}

关于ios - 检查有效的电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36789896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com