Many applications need to validate the email address entered by their users. This post will show how to validate the email address/id in Xcode without using any sort of library.
The normal format of email address is local-part@domain which can be written as :-
1. ios_coderef@blogspot.com
2. ios_codefer@blogspot.co.uk
What i meant to show you above is that there can be either a single dot or two after @
So now let us proceed with the creation of simple method to check whether the entered email address/id is valid or invalid.
Let us define the method in .h file
-(BOOL)validateEmailAddress:(NSString*)emailAddress;
An argument emailID is a NSString object which needs to be checked for email address/validation. The method returns a BOOL
Now let us write the method's body in the .m file
-(BOOL)validateEmailAddress:(NSString*)emailAddress{
NSString *emailFormatA = @"[A-Z0-9a-z._]+@[A-Za-z0-9]+\\.[A-Za-z]{2,4}";
NSString *emailFormatB = @"[A-Z0-9a-z._]+@[A-Za-z0-9]+\\.[A-Za-z]{2,4}+\\.[A-Za-z]{2,4}";
NSPredicate *emailTestA = [NSPredicate
predicateWithFormat:@"SELF MATCHES %@", emailFormat1];
NSPredicate *emailTestB = [NSPredicate
predicateWithFormat:@"SELF MATCHES %@", emailFormat2];
if ( [emailTestA evaluateWithObject: emailAddress] || [emailTestB evaluateWithObject: emailAddress] ) {
return YES;
}
else{
return NO;
}
}
emailFormatA is a string that defines the email address format for ios_coderef@blogspot.com
emailFormatB is a string that defines the email address format for ios_coderef@blogspot.co.uk
emailTestA is a NSPredicate object which is assigned a new predicate formed by creating a new string with a given format (emailFormatA) and parsing the result.
emailTestA is a NSPredicate object which is assigned a new predicate formed by creating a new string with a given format (emailFormatB) and parsing the result.
[emailTestA evaluateWithObject : emailAddress] this returns YES if object (emailAddress) matches the conditions specified by the emailTestA, otherwise NO. Similar for the second condition
So, the if else statement returns YES if the given emailAddress matches either of the two conditions specified by emailTestA and emailTestB else returns NO.
hey ! its not working properly. If i pass wrong email then its also return NO.
ReplyDeleteso that's way its not working properly.
Email Validation
ReplyDeleteThank you.