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

@implementation EmailValidation

// Using NSPredicate

+ (BOOL)isValidEmailAddress:(NSString *)emailAddress {

//Create a regex string
NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" ;

//Create predicate with format matching your regex string
NSPredicate *emailTest = [NSPredicatepredicateWithFormat:
@"SELF MATCHES %@", stricterFilterString];

//return true if email address is valid
return [emailTest evaluateWithObject:emailAddress];
}

// Using NSRegularExpression

+ (BOOL) validateEmail:(NSString*) emailAddress {

NSString *regExPattern = @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$";
NSRegularExpression *regEx = [[NSRegularExpressionalloc]
initWithPattern:regExPattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:emailAddress
options:0
range:NSMakeRange(0, [emailAddress length])];
return (regExMatches == 0) ? NO : YES ;

}

Using SWIFT

func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}

for versions of Swift earlier than 3.0:

func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}

for versions of Swift earlier than 1.2:

func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {
return emailPred.evaluateWithObject(email)
}
return false
}

Swift-4

extension String {
func isValidEmail() -> Bool {
// here, `try!` will always succeed because the pattern is valid
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
}