I’ve been using this extension on on String
to make checking if a string is a valid email easy. If you know a better place this could live, let me know, but an extension on String
felt as good a place as any. I didn’t write the original regex (although I did need to tweak it to make addresses with + in them work), but I’ve tested it and it works well as far as I can tell.
extension String {
func isValidEmail() -> Bool {
if self.isEmpty {
return false
}
guard let regex = try? NSRegularExpression(pattern: "^([a-zA-Z0-9_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", options: []) else {
return false
}
return regex.numberOfMatchesInString(self, options: [], range: NSMakeRange(0, self.characters.count)) == 1
}
}