0

I have implemented this nice solution provided by @Vasily-Bodnarchuk here

I'd like to amend this so I can validate Australian numbers. The problem is that the RegEx validation in the code below appears to only validate US numbers. I have tried a few different values but none seem to work.

Any ideas?

extension String {

    enum RegularExpressions: String {
        case phone = "^\\s*(?:\\+?(\\d{1,3}))?([-. (]*(\\d{3})[-. )]*)?((\\d{3})[-. ]*(\\d{2,4})(?:[-.x ]*(\\d+))?)\\s*$"
    }

    func isValid(regex: RegularExpressions) -> Bool {
        return isValid(regex: regex.rawValue)
    }

    func isValid(regex: String) -> Bool {
        let matches = range(of: regex, options: .regularExpression)
        return matches != nil
    }

    func onlyDigits() -> String {
        let filtredUnicodeScalars = unicodeScalars.filter{CharacterSet.decimalDigits.contains($0)}
        return String(String.UnicodeScalarView(filtredUnicodeScalars))
    }

    func makeAColl() {
        if isValid(regex: .phone) {
            if let url = URL(string: "tel://\(self.onlyDigits())"), UIApplication.shared.canOpenURL(url) {
                if #available(iOS 10, *) {
                    UIApplication.shared.open(url)
                } else {
                    UIApplication.shared.openURL(url)
                }
            }
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Roggie
  • 1,157
  • 3
  • 16
  • 40
  • There are a few 3rd party libraries that validate and format phone numbers of any country. Try searching for one of those. – rmaddy May 07 '18 at 06:10
  • Please look at this too, https://stackoverflow.com/questions/5066329/regex-for-valid-international-mobile-phone-number – PPL May 07 '18 at 06:14

1 Answers1

0

To validate an Australian phone use this:

var phoneExpression = "/^\({0,1}((0|\+61)(2|4|3|7|8)){0,1}\){0,1}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{1}(\ |-){0,1}[0-9]{3}$/"

// Valid
var phoneNumber1 = "0411 234 567"
var phoneNumber2 = "(02) 3892 1111"
var phoneNumber3 = "38921111"
var phoneNumber4 = "0411234567"

// Invalid
var phoneNumber5 = "3892 11"
var phoneNumber6 = "diane 0411 234 567"
var phoneNumber7 = "bob"

check more details

pacification
  • 5,838
  • 4
  • 29
  • 51
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35