1

I am using the following code to validate email address. However, this allows one character after domain. For example, it allows myemail@gmail.c, where it should only allow TLD with at least two characters.

Code:

-(BOOL) IsValidEmail:(NSString *)checkString
{
    NSString *emailRegex =
    @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
    @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
    @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
    @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
    @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
    @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
    @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", emailRegex];

    return [emailTest evaluateWithObject:checkString];

}

Please tell me how do I validate the email?

Community
  • 1
  • 1
TechChain
  • 8,404
  • 29
  • 103
  • 228
  • Please refer to this link: http://stackoverflow.com/questions/3139619/check-that-an-email-address-is-valid-on-ios – Brian Daneshgar Sep 29 '15 at 04:36
  • See also http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address which basically concludes "don't do that". Regex is not a viable solution, as your (broken!) monster regex aptly demonstrates. – tripleee Sep 29 '15 at 08:05
  • It's possible to tweak your existing regex to accept only top level domain name with at least 2 characters (the 4th line): `@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9]{2}(?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"` – nhahtdh Sep 29 '15 at 11:12

1 Answers1

2
-(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];
}

The top level domain can go upto 63 characters, so change the 4 to your business decision in the regular expression. e.g.

@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,63}";
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
  • Just in case anyone had the same question I had when I looked at this: the `"\\."` is there because `"\\"` turns into `"\"` when the string is interpreted before trying to match the regex, which then combined with the following `.` becomes `"\."`, since the period needs an escape character (otherwise it would represent just one character of any value). – adamsuskin Sep 29 '15 at 04:44
  • 1
    This totally disregards TLD domain name such as `.ninja`, `online`, `global`, etc. – nhahtdh Sep 29 '15 at 07:43
  • @nhahtdh the top domain can go upto `63` chars and the OP can change the last digit `4` to `6` or `63` depending upon his need. – Inder Kumar Rathore Sep 29 '15 at 08:33