32

I'm using this code on an email field:

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email address")]
    public string Email { get; set; }

[DataType(DataType.EmailAddress)] does not work (validation does not occur no at a server not on the client side).

I am not sure if I should implement myself a Custom Attribute or I can use one included with MVC 3.

Could you please suggest me a solution for creating a custom attribute in case I need to.

I read also about some additional extensions, example http://nuget.org/packages/DataAnnotationsExtensions.MVC3

Would you suggest it to me?

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • I had a similar issue and just used a `RegularExpression(...)` to do the email address validation. – bluevector Jul 12 '12 at 14:05
  • 3
    Please expand upon `Does not work`. The input element in the DOM (if you use `HTML.InputFor(m => m.Email)` should have the `type="email"` attribute set. – Rich O'Kelly Jul 12 '12 at 14:05
  • I made an edit to my question, the email field is not validated client and server – GibboK Jul 12 '12 at 14:07
  • jonnyGold find out my answer, I think can solve also your problem. thanks for your message – GibboK Jul 12 '12 at 14:16
  • @GibboK Have a look at http://stackoverflow.com/questions/2391423/is-the-datatypeattribute-validation-working-in-mvc2 – Rich O'Kelly Jul 12 '12 at 14:16

6 Answers6

50

You could use the usual DataAnnotations library by just using [EmailAddress]

using System.ComponentModel.DataAnnotations;
    [Required]
    [EmailAddress]
    public String Email { get; set; }

Also just for reference, here's the regular expression version of this validation:

    [RegularExpression(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-‌​]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]
    public String Email {get; set;}

Best of luck!

Tom Kidd
  • 12,830
  • 19
  • 89
  • 128
SarahK
  • 624
  • 1
  • 4
  • 7
  • 2
    Hey escist, try this one instead: [RegularExpression(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]' – SarahK Jul 19 '12 at 14:05
  • 6
    Stop validating email addresses with regular expressions already http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/ – Luc Jan 07 '14 at 07:29
  • @Luc you do realise that even `EmailAddressAttribute` validates addresses using regular expression? – Robert Koritnik Feb 14 '16 at 12:18
  • 3
    @RobertKoritnik That may be, but I trust something made by a big company a lot more than a random comment. Plus, if the regex turns out to be wrong, which it probably is, it can be centrally updated for everyone (simply update .NET). I still hate validation beyond "does it contain an @ symbol" but I'm much more in favor of a language feature versus someone hardcoding a regex. – Luc Feb 14 '16 at 16:20
  • @Luc: The best thing would of course be if there was some type `Email` which would work similarly to `Uri` type. You could then simply ask it what's the *private part* or *TLD* and you'd get the answer. It would also be much better at transforming email addresses which at the moment can't be done with existing RegEx that .net uses. One has to do parsing itself and *mask* emails however they please. Usually using Regexes... As I do... ;) – Robert Koritnik Feb 15 '16 at 12:32
  • MVC4 doesn't have `EmailAddressAttribute` in `System.ComponentModel.DataAnnotations` – Paul Apr 30 '16 at 11:35
13

At the moment I have solved my problem using DataAnnotationsExtensions

it just works, you add their library with NuGet

using DataAnnotationsExtensions;


[Required]
    [DataType(DataType.EmailAddress)]
    [Email]
    public string Email { get; set; }
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 5
    As of today: `[EmailAddress]` – Rafael Aug 10 '17 at 12:45
  • 1
    Also today you don't need the DataTypeAttribute when you use the EmailAddressAttribute, because the EmailAddressAttribute derives from DataTypeAttribute and initializes the base constructor with DataType.EmailAddress – René Aug 10 '21 at 09:10
6

It looks like all the answers focus on the Data Model while this issue can be affected by the View itself.

The following on MVC .NET 4.5 is working alright:

Data model:

[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email")]
public string Email { get; set; }

Razor View:

@Html.LabelFor(model => model.Email)
@Html.EditorFor(model => model.Email)

Note: do not need to add [EmailAddress] attribute. If you use [DataType(DataType.EmailAddress)] along with @Html.EditorFor() in your View, you should be fine.

As highlighted with rich.okelly, at the end you want your input rendered as <input type="email" />.

Felix
  • 336
  • 2
  • 6
  • 1
    try entering the value a@a The form is submitted and it passes validation on both the client and server. If you use EmailAddress in the model, it passes client-side and fails server-side. – Bob May 08 '15 at 18:57
  • This however isn't working ``, and there's no other asp tag that works – Etienne Charland Sep 29 '20 at 19:39
5

May be this will be helpful for someone. Following works for me

[Required(ErrorMessage = "*")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }

But does not work following

[Required(ErrorMessage = "*")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }

I am using MVC 5 & .NET 4.5

Seth
  • 10,198
  • 10
  • 45
  • 68
msib
  • 93
  • 1
  • 6
  • 2
    It appears that the [DataType(DataType.EmailAddress] attribute only appears to validate if the [Required] attribute is also specified. If you just want to validate the entry if it exists it seems that the [EmailAddress] attribute is better suited – Neilski Jan 19 '15 at 11:43
2

As Felix mentioned, the problem is on the View level, you need to use EditorFor() in your View instead of TextBoxFor(), the EditorFor() will render:

<input type="email" />

which will trigger the validation, while TextBoxFor() will render:

<input type="text" />

So in order to validate your entered email address, you need (in combination with EditorFor()) to use only:

[DataType(DataType.EmailAddress)]
public string Email { get; set; }

This way, your entered value for email will be always validated, but if you don't enter a value for email, nothing will happen (unless you specified the [Required] attribute), the form will be submitted with an empty email address.

Stacked
  • 6,892
  • 7
  • 57
  • 73
0

[DataType(DataType.EmailAddress)] can't recognize @ and [EmailAddress] can't recognize .com , so use RegularExpression :

[RegularExpression(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-‌​]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]
M Komaei
  • 7,006
  • 2
  • 28
  • 34