Skip to content

Instantly share code, notes, and snippets.

@illescasDaniel
Forked from DaveWoodCom/String+Email.swift
Last active March 26, 2017 21:18
Show Gist options
  • Save illescasDaniel/d38dbe4dbd4e2c527facf80021d9f3b5 to your computer and use it in GitHub Desktop.
Save illescasDaniel/d38dbe4dbd4e2c527facf80021d9f3b5 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)
import Foundation
extension String {
mutating 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 textRange = NSRange(location: 0, length: self.characters.count)
let matches = emailDetector.matches(in: self, options: .anchored, range: textRange)
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