How to validate email address in iOS/Objective-C


Background:~

Unlike other languages, in iOS sometimes we need to verify email address entered by user, especially in registration & login process.

Following function will check the entered email address is valid or not and return the value based on validation.

Implementation:~

Utility.h

#import <Foundation/Foundation.h>

@interface Utility : NSObject

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

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

@end

Utility.m

#import "Utility.h"

@implementation Utility

// 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 ;

}

How to Use:~

Validate email address by calling any of the above method. For example, 

[Utility isValidEmailAddress:@"milan@example.com"]; OR 
[Utility validateEmail:@"sam@example.com"];
Advertisements

2 thoughts on “How to validate email address in iOS/Objective-C

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s