0

I am Trying to validate email address field using below regex

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

But its getting failed for validating below cases.

i) test@-gmail.com

ii) test..test@gmail.com

iii) .test@gmail.com

iv) test.@gmail.com

Please suggest me what modification do I need for considering these cases.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Nilesh Mahajan
  • 607
  • 4
  • 16
  • 1
    that will also fail with unicode TLDs and whatnot. http://www.regular-expressions.info/email.html – Marc B Jun 09 '15 at 14:33
  • Do you know any alternate way or any other Regex that works in these cases? – Nilesh Mahajan Jun 09 '15 at 14:35
  • did you even bother looking at the link I provided? – Marc B Jun 09 '15 at 14:38
  • Have you considered this discussion? http://stackoverflow.com/questions/800123/what-are-best-practices-for-validating-email-addresses-in-objective-c-for-ios-2 – blong Jun 09 '15 at 14:48
  • 1
    Yes. I am looking over the link which you shared. and trying to make some modifications in my regex – Nilesh Mahajan Jun 09 '15 at 14:49
  • I hv tried some other modifications but those are not working as will. – Nilesh Mahajan Jun 09 '15 at 15:00
  • Thanks Mark Your answer helped me. I got one solution. I am checking the two regex now. one which is posted in question and one which is posted in comments. if both are true then it works fine in all the cases for me. Thanks for help – Nilesh Mahajan Jun 09 '15 at 15:29
  • http://regular-expressions.info/email.html useful link – Nilesh Mahajan Jun 09 '15 at 15:31
  • I guess its enough `\A[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@ (?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\z` instead of using two regex. – TheTiger Feb 09 '18 at 12:54

1 Answers1

0

Try this.

-(BOOL)emailValidation:(NSString *)str{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest =[NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL myStringMatchesRegEx=[emailTest evaluateWithObject:str];

    if (myStringMatchesRegEx == 0) {
        return FALSE;
    }
    return TRUE;
}

and check email valid or not.

if(![self emailValidation:txtEmail.text]){
        [appDelegate showAlert:@"Alert" message:@"Invalid Email Address"];
}
Keyur Akbari
  • 182
  • 1
  • 13