Skip to content

Instantly share code, notes, and snippets.

@DaveWoodCom
Last active February 28, 2021 16:45
Show Gist options
  • Save DaveWoodCom/4f751193cdb7d3767e5a to your computer and use it in GitHub Desktop.
Save DaveWoodCom/4f751193cdb7d3767e5a 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"
}
}
@strzempa
Copy link

strzempa commented Apr 17, 2020

Swift 5:

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.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