Search code examples
c#regexemail-validation

Incorporating length validation into an existing email address format regex


I am using this regex in C# for email format validation based on information from http://www.regular-expressions.info/email.html:

Regex.IsMatch("[email protected]", 
              @"^[A-Z0-9'._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$",RegexOptions.IgnoreCase);

I would also like to validate that the total length of the email is between 5 - 254 characters. How should this regex be modified to satisfy the length condition? I don't want to check the length of the string in C# explicitly.


Solution

  • Although it's probably cleaner to just do the length checks separately, you can incorporate your length constraint by adding a noncapturing lookahead to the start of your expression:

    ^(?=.{5,254})[A-Z0-9'._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$