How to validate email on textField in IOS

Something that every app developer has to deal with at some point or another is string validation, with the most common problem being email validation. That is because every single online service has a login or signup view controller. It is so common you almost wonder why Apple and every single other language developer doesn’t have a built in version.

Below I have shared a very simple email validation method using NSPredicate. You can use this method to create a new NSString’s Category file and have this method available anywhere in your app directly from any NSString object.

This method that I am using, uses NSRegularExpression. Taken directly from the Apple website:

The NSRegularExpression class is used to represent and apply regular expressions to Unicode strings. An instance of this class is an immutable representation of a compiled regular expression pattern and various option flags. The pattern syntax currently supported is that specified by ICU. The ICU regular expressions are described at http://userguide.icu-project.org/strings/regexp .

The fundamental matching method for NSRegularExpression is a Block iterator method that allows clients to supply a Block object which will be invoked each time the regular expression matches a portion of the target string. There are additional convenience methods for returning all the matches as an array, the total number of matches, the first match, and the range of the first match.

Using Objective-C

Using SWIFT

for versions of Swift earlier than 3.0:

for versions of Swift earlier than 1.2:

Swift-4