emin
Posted on April 3, 2022
Hey there! I won't keep you long, just thought to share this quick snippet with you.
I am currently working on a new project, and started migrating everything from the old one where I had bunch of small helper methods, and now, I am cherry picking the best ones or re-working some older ones.
However, for this email checker i don't think in would ever need a new one.
This extension with check if the email has a valid format. I went through all kinds of iterations and finally stumbled upon this gem online. 💎
Note: This will only check if the FORMAT is valid. It will not verify if that email exists or not. I never needed that check so far, and most of the time you are sending a verification code or something from your server so all non-existent emails are discarded that way.
extension String {
func isValidEmail() -> Bool {
// `try!` will always succeed because the pattern is valid
let regex = try! NSRegularExpression(pattern: "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" +
"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" +
"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" +
"z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" +
"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" +
"9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" +
"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", options: .caseInsensitive)
return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
}
Thank you for reading! Feel free to get in touch on Twitter
Cheers! 🍻
Posted on April 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.