Skip to content

Instantly share code, notes, and snippets.

@rlaguilar
Forked from DaveWoodCom/String+Email.swift
Created September 26, 2017 17:49
Show Gist options
  • Save rlaguilar/a238f4b373cb7e38511503c0853e077f to your computer and use it in GitHub Desktop.
Save rlaguilar/a238f4b373cb7e38511503c0853e077f 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.lowercaseString.hasPrefix("mailto:") else { return false }
guard let emailDetector = try? NSDataDetector(types: NSTextCheckingType.Link.rawValue) else { return false }
let matches = emailDetector.matchesInString(self, options: NSMatchingOptions.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