1

I have the following regex for the email validation:

private const string ValidEmailRegexPattern = @"^(?:[^@\s\\(),:;<>[\]""]+|(?:(?:^|\.)""(?:[^\r\\"";]|(?:\\[\\""]))*"")+)+(?<=^.{1,64})@[^\s~!@#$%^&*()=+_{}\|;,`'""?<>]{1,256}$";

public static bool IsValidEmail(string email)
{
     return !string.IsNullOrWhiteSpace(email) && ValidEmailRegex.IsMatch(email);
}

But it is froze when input is valid email, but with maximum valid length (254 symbols) like this:

"123...@gmail.com" - 254 symbols, including 244 numbers and @gmail.com.

How to change my regex? I want that my program can handle that type of email address.

1 Answers1

4

You can use the MailAddress class to validate the email instead of validating it using the regex.

MailAddress m = new MailAddress(email);

From MSDN

Instead of using a regular expression to validate an email address, you can use the System.Net.Mail.MailAddress class. To determine whether an email address is valid, pass the email address to the MailAddress.MailAddress(String) class constructor.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 2
    You can vote to close as duplicate instead of duplicating answers. – CodeCaster Nov 12 '15 at 13:41
  • 2
    @CodeCaster:- Will take care in future. Didn't checked for duplicates at that time! – Rahul Tripathi Nov 12 '15 at 13:42
  • 2
    @CodeCaster, that is not prohibited. – Giorgi Nakeuri Nov 12 '15 at 13:43
  • @Giorgi no it is not and I am not saying it is, but you'd expect better from an 80K rep user. That's all. This answer does not explain _why_ you should use this approach, and it does not explain that the only valid form of email validation is to send an email to the provided address, but hey, give him four upvotes. Or five. – CodeCaster Nov 12 '15 at 13:43
  • 2
    @RahulTripathi Thank you for support! –  Nov 12 '15 at 13:49
  • 1
    MailAddress does not handle 255 symbols(invalid email). So using this class its not a solution – Anatoly Nov 12 '15 at 14:17