What are best practices for validating email addresses in Swift?

animal_chin picture animal_chin · Oct 3, 2014 · Viewed 19.3k times · Source

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

Answer

Craig Otis picture Craig Otis · Oct 3, 2014

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