0

I am using the following code to check the validation of my email which is entered in the uitextfield. But it is returning true when I enter abcd@m.com.com it is not returning false.

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];

Anyone can suggest me ?

Sharme
  • 625
  • 4
  • 10
  • 28
  • 1
    There are many discussions about using regular expressions for validating email addresses, for example here: http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address. - Also `abcd@m.com.com` looks "well-formed" to me (but I may be wrong!) and matches the regular expression. Why do you expect to get false? – Martin R Apr 02 '14 at 07:42
  • `abcd@m.com.com` can be a valid email address! – lootsch Apr 02 '14 at 07:47
  • But I don't need the abcd@m.com.com. I need like abcd@m.com – Sharme Apr 02 '14 at 07:48

2 Answers2

1

Email validation for ios code.

- (BOOL)validateEmailWithString:(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];
}

Textfield delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    if ([self validateEmailWithString:textField.text])
    {
        Nslog(@"Valid");
    }
    else
    {
        Nslog(@"Not Valid");
    }

}
Kirit Modi
  • 23,155
  • 15
  • 89
  • 112
1

Don't exclude the domain m.com.com, as it's a possible subdomain of com.com (wich maybe looks strange, but is a valid - and btw. real - domain).

If you still want to exclude all subdomains (saying: only allow one . after @) you would exclude email addresses like:

  • example@provider.co.uk
  • example@groups.google.com
  • example@press.apple.com
  • example@support.stackexchange.com
  • abcd@m.com.com

So, you maybe don't want to exclude them.

lootsch
  • 1,867
  • 13
  • 21