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.
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.
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 }
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() { }
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