0

I have the following ViewModel, it has a data annotation to validate the email and a regular expression to make sure the email is in lower-case and without spaces.

[Required]
[MaxLength(200)]
[EmailAddress]
[RegularExpression(@"^[a-z0-9\-_\.\@\:]+$", ErrorMessage = "Characters are not allowed.")]
public string Email { get; set; }

For example:

  • "test@hotmail.com" = OK
  • " test@hotmail.com" = NOT OK
  • "TEst@hotmail.com" = NOT OK
  • "test@hotmail.com " = NOT OK

I can get the upper-case error but not the space error. However, if I comment [EmailAddress] I can get both errors, upper-case and space.

sticky bit
  • 36,626
  • 12
  • 31
  • 42
Bug
  • 832
  • 2
  • 9
  • 37
  • 5
    Please, have a look at these sites: [TLD list](https://www.iana.org/domains/root/db); [valid/invalid addresses](https://en.wikipedia.org/wiki/Email_address#Examples); [regex for RFC822 email address](http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) – Toto Apr 09 '19 at 10:29
  • 1
    You can't easily verify email addresses with a regex, unless it's a *very* complex one, like the one pointed to by Toto. Your regex drops valid addresses without preventing obviously wrong ones like `@abcd`. – Panagiotis Kanavos Apr 09 '19 at 10:31
  • Why does it need to be in lower case? Email usernames are case sensitive. Also, could you not do `_email = String.ToLower(value);` for the setter? (with a backing field obviously) to get around the casing issue if it is actually a requirement? – IAmJersh Apr 09 '19 at 10:36
  • 1
    As one of the duplicates shows, .NET 4.5 introduced the [EmailAddress](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.emailaddressattribute?view=netframework-4.7.2) data annotation attribute. [Its source code](https://referencesource.microsoft.com/#System.ComponentModel.DataAnnotations/DataAnnotations/EmailAddressAttribute.cs) shows that the required regex is rather complex. The regex is so complex that the code adds a 2 second timeout to the regex – Panagiotis Kanavos Apr 09 '19 at 10:36
  • You should also consider allowing the user to enter leading and trailing spaces and then triming in code once submitted otherwise this could frustrate the user as spaces as by nature invisible and difficult for the user to spot. Same goes for case you could fix this automatically. – apc Apr 09 '19 at 10:37

0 Answers0