Does the DataTypeAttribute on a model do validation in MVC 3?

Viewed 13225

The default ASP.net MVC 3 Internet Application template includes the following model:

public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

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

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

In the Account/Register action it is asking for an email address, but it seems you can type anything in this field and it will accept it.

Does the DataType(DataType.EmailAddress) actually trigger validation? It seems like it does not. If it doesn't validate the type, then what is its purpose?

6 Answers

There is NO validation associated with the DataType attributes in the current release of MVC3.

New attributes deriving from this attribute are shown in MVC Futures and add this validation process. For example, EmailAddressAttribute.

Related