Reputation: 77
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?
Upvotes: 3
Views: 1845
Reputation: 79636
// 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)")
Upvotes: 1