Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
}
like image 371
animal_chin Avatar asked Oct 03 '14 14:10

animal_chin


2 Answers

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
like image 82
Craig Otis Avatar answered Oct 02 '22 18:10

Craig Otis


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
like image 31
Jordi Bruin Avatar answered Oct 02 '22 19:10

Jordi Bruin