January 9, 2014

Email address validation in iOS

Background :~

Unlike other technologies, in iOS sometimes we need to verify email address entered by user, especially in registration & login screen. Following function will check the entered email address is valid or not and return the value based on validation.
Implementation :~


#import <Foundation/Foundation.h>

@interface Utility : NSObject

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

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



#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 = [NSPredicate predicateWithFormat:
                             @"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 = [[NSRegularExpression alloc]

   NSUInteger regExMatches = [regEx numberOfMatchesInString:emailAddress
                                                      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:@""]; OR

[Utility validateEmail:@""];