Thursday, 18 April 2013

Email validation in objective c

If your are designing signup screen in iOS app, you need to validate email provided by user. In this post we will learn ho validate email and show alert if provided email is wrong.

For this we will use NSPredicate and regular expression.



 (BOOL)validateEmail:(NSString *)emailStr 
    
    NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
    
    NSString *emailRegex = YES ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:emailStr];

}

Now show alert if email is invalid


if(![self validateEmail:[aTextField text]]) {
        // user entered invalid email address
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Enter a valid email address." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show]; 
        [alert release]; //if ARC is disable then write this line otherwise not
 }

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi friends if you want to get idea about email validation service so i think this website is very help for you. Here you will get lots of idea about it. I hope you will be happy with this website. Thanks for join with this community.

    ReplyDelete
  3. The post is written in very a good manner and it contains many useful information for me. https://verifications.io

    ReplyDelete
  4. We ensure you only send an email to real users and protect your reputation, Boost your email campaign, and save money with Emailmarker. email validation service

    ReplyDelete