1

I'm working with ASP.NET MVC 3 C# and I have this regex:

@"([a-zA-Z0-9%._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4})+"

It works for almost all cases, unless after the @ have less than 2 characters.

Ex: stackoverflow@ab.com < Valid e-mail.
stackoverflow@a.com < Invalid e-mail, but my regex don't works.

I don't found something like this on forum and i I know almost nothing about regex. Someone can help with this? Thanks. (Sorry for bad english).

3 Answers3

3

You're not escaping the periods (.) in your RegExp so they are basically an ANY CHARACTER placeholder.

The domain portion of an email address (after the @) can only contain letters, numbers, periods and hyphens. The first and last character and the character before and after a period must be a letter or number. This may have changed because of new allowances foreign characters.

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
  • 1
    if you still ask why x@a.com fails, the explanation is as follows... the Regex is matching the 4 last characters of the address (i.e., ".com") because of the range 2-4 characters at the end of your pattern, while the last dot in your pattern is matching the "a", which leaves nothing for the "+" pattern to find and it requires at least one character, so the pattern fails to match. – Les Nov 20 '13 at 13:14
1

http://www.regular-expressions.info/email.html

RFC 5322:

(?:[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])+)
     \])
0

As this is C# you can always create your own attributes to make this look a bit more appealing.

using System.ComponentModel.DataAnnotations;
class EmailValidationAttribute : RegularExpressionAttribute
{
    public EmailValidationAttribute()
        : base("^[a-zA-Z0-9_\\+-]+(\\.[a-zA-Z0-9_\\+-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.([a-zA-Z]{2,4})$") { }
}


class EmailTest
{
    [EmailValidation(ErrorMessage="Please Enter a valid email address")]
    public String Email { get; set; }

}

This should take into account most cases, you can always also combine it with Robert P's answer to get a better regex, but for what I can see it does not take into account people writing their emails in capital letters.