0

I have a UITextField that accepts a phone number i want to validate it if that is an american formatted phone number. i know that in swift you have an out of the box fix for that ?

do you know of a regex or a way fo validate that that can work on swift 4 ?

thedp
  • 8,350
  • 16
  • 53
  • 95
Chief Madog
  • 1,738
  • 4
  • 28
  • 55
  • 5
    Phone number validation is kinda tricky thing, so I advise you to use some ready-to-use pod, like [PhoneNumberKit](https://github.com/marmelroy/PhoneNumberKit) instead of writing own ad-hoc validator. – user28434'mstep Nov 22 '18 at 09:22

2 Answers2

2

Use this regular expression:

(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}

Code:

let phoneNumber = "+1 (123) 456-7890" //Replace it with the Phone number you want to validate
let range = NSRange(location: 0, length: phoneNumber.count)
let regex = try! NSRegularExpression(pattern: "(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}")
if regex.firstMatch(in: phoneNumber, options: [], range: range) != nil{
    print("Phone number is valid")
}else{
    print("Phone number is not valid")
}
Daniyal Raza
  • 352
  • 3
  • 13
0

Use this regular expression

^[1{1}]\\s\\d{3}-\\d{3}-\\d{4}$

Use like this :

isValidMobile(testStr : "1 555-555-5555")

This will return true

isValidMobile(testStr : "1 555-555-55555")

This will return false

Function will be like this :

func isValidMobile(testStr:String) -> Bool {        
    let mobileRegEx = "^[1{1}]\\s\\d{3}-\\d{3}-\\d{4}$"
    let mobileTest = NSPredicate(format:"SELF MATCHES %@", mobileRegEx)
    return mobileTest.evaluate(with: testStr)
}
Mahesh Shahane
  • 489
  • 5
  • 16