What is the cleanest way to validate an email address that a user enters on iOS 2.0?
NOTE: This is a historical question that is specific to iOS 2.0 and due to its age and how many other questions are linked to it it cannot be retired and MUST NOT be changed to a "modern" question.
The best solution I have found so far (and the one I ended up going with) is to add RegexKitLite To the project which gives access to regular expressions via NSString Categories.
It is quite painless to add to the project and once in place, any of the regular expression email validation logic will work.
While the focus on regular expressions is good, but this is only a first and necessary step. There are other steps that also need to be accounted for a good validation strategy.
Two things on top of my head are :
DNS validation to make sure the domain actually exists.
After dns validation, you can also choose to do an smtp validation. send a call to the smtp server to see if the user actually exists.
In this way you can catch all kinds of user errors and make sure it is a valid email.
This function is simple and yet checks email address more thoroughly. For example, according to RFC2822 an email address must not contain two periods in a row, such as firstname..lastname@domain..com
It is also important to use anchors in regular expressions as seen in this function. Without anchors the following email address is considered valid: first;name)lastname@domain.com(blah because the lastname@domain.com section is valid, ignoring first;name) at the beginning and (blah at the end. Anchors force the regular expressions engine to validate the entire email.
This function uses NSPredicate which does not exist in iOS 2. Unfortunately it may not help the asker, but hopefully will help others with newer versions of iOS. The regular expressions in this function can still be applied to RegExKitLite in iOS 2 though. And for those using iOS 4 or later, these regular expressions can be implemented with NSRegularExpression.
See validate email address using regular expression in Objective-C.
I have found that using a regular expression works quite well to validate an email address.
The major downside to regular expressions of course is maintainability, so comment like you have never commented before. I promise you, if you don't you will wish you did when you go back to the expression after a few weeks.
Here is a link to a good source, http://www.regular-expressions.info/email.html.
The answer to Using a regular expression to validate an email address explains in great detail that the grammar specified in RFC 5322 is too complicated for primitive regular expressions.
I recommend a real parser approach like MKEmailAddress.
As quick regular expressions solution see this modification of DHValidation: