3

I have a UITextField where we can enter either email id or our phone number. My question is it possible to check whether the text entered in the UITextField is a phone number or emailID on a button click in Swift3? Currently i am using the following code:

func isNumber(text:String)->Bool
{
    if let intVal = text.toInt()
        {return true}
    else
        {return false}
}

But it can validate, input is integer or not. Is it possible to know whether the input is emailID or phone number?

Krunal
  • 77,632
  • 48
  • 245
  • 261
  • Possible duplicate of [How to check is a string or number](https://stackoverflow.com/questions/26545166/how-to-check-is-a-string-or-number) – Mo Abdul-Hameed Jun 30 '17 at 15:03
  • Use regex for email – Krunal Jun 30 '17 at 15:05
  • 1
    What's supposed to happen if the user enter phone numbers like `+1(512)...` ? By the way `toInt()` is Swift 1. Consider to update. – vadian Jun 30 '17 at 15:10
  • @vadian In that case a regex for Phone number can be used, if phone number has specific characters, along with numbers – Krunal Jun 30 '17 at 15:17

1 Answers1

1
// Datatype specifier
enum DataType: Int {
  case Other = 0  // This can be string
  case Number = 1
  case Email = 2
}



// Validate Email
func isEmail(emailString: String) -> Bool {
    // Sample regex for email - You can use your own regex for email
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegex)
    return emailTest.evaluate(with: emailString)
}


// Check Datatype
func checkDataType(text: String)-> DataType {
    if let intVal = text.toInt() {
        return DataType.Number
    } else if isEmail(emailString: text) {
       return DataType.Email
    } else {
       return DataType.Other
   }
}

// print datatype
let dataType = checkDataType(text: "Your Input String")
print("DataType = \(dataType)")
Krunal
  • 77,632
  • 48
  • 245
  • 261