Validation of email in swift iOS application

Swift 4.2 and Xcode 10

For me, other answers were returning true if there are more then two dots after the domain name. I found this answer where it handles that condition properly.

func isValidEmail(testStr:String) -> Bool {
    let emailRegEx = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{1,4}$"
    let emailTest = NSPredicate(format:"SELF MATCHES[c] %@", emailRegEx)
    return emailTest.evaluate(with: testStr)
}

Happy Coding 😀


You can validate email using a simple regex function which returns true if it's valid otherwise false

You can validate it when user hits Done/Enter on keyboard event, such as editingDidEnd. You can bind it from storyboard to class file like,

@IBAction func onPressDone(sender: UITextField){
    if txtEmaildAddress.text.isEmpty {
        println("enter email address") //prompt ALert or toast
    }
    else if self.validate(txtEmaildAddress.text) {
        println("Invalid email address") // prompt alert for invalid email
    }
}

func validate(YourEMailAddress: String) -> Bool {
    let REGEX: String
    REGEX = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
    return NSPredicate(format: "SELF MATCHES %@", REGEX).evaluateWithObject(YourEMailAddress)
}

May help this method to validate easily.

HTH, Enjoy Coding !!

Tags:

Ios

Xcode

Swift