Email validation in Swift

darthpelo
1 min readOct 25, 2016

--

Update 03/08/2019

I published a new article that shows how to improve Input Validation in Swift, using the email address validation as an example. I took the opportunity to add a small improvement, not to the NSPredicate itself, but adding a new important check to the address, related to the maximum the length.

Update 19/03/2018

Thanks to my collegues Ata Cengiz, I update the regular expression that now accepts an username with uppercase, but not a domain with uppercase.

Since the beginnig of my work experience with iOS (2010) I need to validate email format and I always used the solution proposed by Matt Gallagher in the 2009: http://www.cocoawithlove.com/2009/06/verifying-that-string-is-email-address.html

The solution is simple:

use NSPredicate to validate a String with a regular expression based on a complete verification of RFC 2822. Matt Gallagher created the Objective-C version of a previous solution that you can find here.

I wrote the Swift version and because I work, at least, on 2 projects that required to validete an email address every year, I keep update this function every time Apple update Swift. Enjoy it 🙂

--

--

darthpelo

Software Engineer & Senior iOS developer at @mobiquityinc NL. Craft Beer addict. Il caso non esiste. Il caos sì /The case does not exist. The chaos exists.