Labels

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 :~


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 = [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]
                                 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"];