Search code examples
iosobjective-ciphoneswiftnspredicate

What are best practices for validating email addresses in Swift?


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];
}

Solution

  • 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