I'm looking for the simplest and cleanest method for validating email (String) in Swift. In Objective-C I used this method, but if I rewrite it to Swift, I get an error 'Unable to parse the format string' when creating predicate.
- (BOOL) validateEmail: (NSString *) candidate {
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:candidate];
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With