user5513630
user5513630

Reputation: 1699

Check the valid phone number

I have one text field for enter the phone number and user have to press OK button.

Then I write some function to check whether entered number is valid number or 10 digit number. And I don't want to add country code. That I have separately.

But when I press OK button its give me uialert - wrong number for all number including my own number. I don't know any code I missed?

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

Updated :

 @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


  }

Upvotes: 10

Views: 28170

Answers (6)

Mahendra Liya
Mahendra Liya

Reputation: 13218

Modifying @A.G's answer to update to 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
        }
    }
}

Upvotes: -1

Easy validation for Indian 10 digit mobile number

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

Upvotes: 0

cody
cody

Reputation: 148

Amended @Alvin George code for Swift 4 that also accepts only 10 digit phone numbers:

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

Upvotes: 0

Alvin George
Alvin George

Reputation: 14296

Try this.

Make an extension to 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: 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
        }
    }
}

Older Swift Versions

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

Usage:

override func viewWillAppear(animated: Bool) {

//Sample check
let phoneString = "8888888888"

let phoneNumberValidator = phoneString.isPhoneNumber
print(phoneNumberValidator)

}

Upvotes: 26

Sourabh Kumbhar
Sourabh Kumbhar

Reputation: 1054

Try this for Indian 10 digit mobile number validation

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
}

Upvotes: 2

SpaceX
SpaceX

Reputation: 2890

Swift 3

For those of you who would like the phone number to have a minimum of 10 characters use the below code (Amended @Alvin George code)

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

Usage

ooverride func viewDidLoad() {
    super.viewDidLoad()

    //Example
    let phoneNumberString = "8500969696"

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

}

Upvotes: 2

Related Questions