Email model validation with DataAnnotations and DataType

lifeofbenschi picture lifeofbenschi · Jan 24, 2012 · Viewed 93.1k times · Source

I have following model:

public class FormularModel
{
    [Required]
    public string Position { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Required]
    public string Webcode { get; set; }
}

Required validation works fine. But when i try with DataType it doesn't react.

Here is my razor code for the email control:

   @Html.TextBoxFor
          (model => model.Email, 
           new { @style = "width: 175px;", @class = "txtField" }
          ) * 

So, anyone know an answer?

TIA

Answer

Leniel Maccaferri picture Leniel Maccaferri · Jan 24, 2012

DataType attribute is used for formatting purposes, not for validation.

I suggest you use ASP.NET MVC 3 Futures for email validation.

Sample code:

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

If you happen to be using .NET Framework 4.5, there's now a built in EmailAddressAttribute that lives in System.ComponentModel.DataAnnotations.EmailAddressAttribute.