What are best practices for validating email addresses in Swift?
Seems pretty straightforward. If you're having issues with your Swift conversion, if might be beneficial to see what you've actually tried.
This works for me:
func validateEmail(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(candidate)
}
validateEmail("[email protected]") // true
validateEmail("invalid@@google.com") // false
Swift 3.0 version
func validateEmail(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)
}
validateEmail("[email protected]") // true
validateEmail("invalid@@google.com") // false