Skip to content

Instantly share code, notes, and snippets.

@ezefranca
Forked from DaveWoodCom/String+Email.swift
Last active August 7, 2017 22:51
Show Gist options
  • Save ezefranca/e0c1eef5adfdf36d208aa8309547ebdb to your computer and use it in GitHub Desktop.
Save ezefranca/e0c1eef5adfdf36d208aa8309547ebdb to your computer and use it in GitHub Desktop.
Swift method to check for a valid email address (uses Apples data detector instead of a regex)
extension String {
func isValidEmail() -> Bool {
guard !self.lowercased().hasPrefix("mailto:") else { return false }
guard let emailDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { return false }
let matches = emailDetector.matches(in: self, options: NSRegularExpression.MatchingOptions.anchored, range: NSRange(location: 0, length: self.characters.count))
guard matches.count == 1 else { return false }
return matches[0].url?.scheme == "mailto"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment