Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate an e-mail address in swift?

Does anyone know how to validate an e-mail address in Swift? I found this code:

- (BOOL) validEmail:(NSString*) emailString {      if([emailString length]==0){         return NO;     }      NSString *regExPattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";      NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];     NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];      NSLog(@"%i", regExMatches);     if (regExMatches == 0) {         return NO;     } else {         return YES;     } } 

but I can't translate it to Swift.

like image 225
Giorgio Nocera Avatar asked Aug 24 '14 11:08

Giorgio Nocera


People also ask

How do I validate my email SMTP?

After the DNS lookup, you can validate the email address via SMTP connection. You need to connect to the chosen SMTP server and request whether an email address exists. If the server replies with ( 250 OK ), the email address is valid. If the client gets a negative response ( 550-5.1.


2 Answers

I would use NSPredicate:

func isValidEmail(_ email: String) -> Bool {             let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"      let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)     return emailPred.evaluate(with: email) } 

for versions of Swift earlier than 3.0:

func isValidEmail(email: String) -> Bool {     let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"      let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)     return emailPred.evaluate(with: email) } 

for versions of Swift earlier than 1.2:

func isValidEmail(email: String) -> Bool {     let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"      if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {         return emailPred.evaluateWithObject(email)     }     return false } 
like image 170
Maxim Shoustin Avatar answered Sep 19 '22 12:09

Maxim Shoustin


As a String class extension

SWIFT 4

extension String {     func isValidEmail() -> Bool {         // here, `try!` will always succeed because the pattern is valid         let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)         return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil     } } 

Usage

if "rdfsdsfsdfsd".isValidEmail() {  } 
like image 35
Arsonik Avatar answered Sep 17 '22 12:09

Arsonik