asp.net-mvc-3validationattributesasp.net-mvc-validation

DataType attribute doesn't work


In ASP.NET MVC 3 web application I have a viewmodel with properties which marked with DataType attributes, but they don't do actual validation on cliant side, and on server side, Why?

public class RegisterModel
{
    [Required(ErrorMessage = "Phone number is required")]
    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Phone number")]
    public string PhoneNumber { get; set; }

    [Required(ErrorMessage = "E-mail address is required")]
    [DataType(DataType.EmailAddress, ErrorMessage = "Please enter a valid date (ex: 2/14/2011)")]
    [Display(Name = "E-mail address")]
    public string Email { get; set; }
}

Thanks for replying.


Solution

  • DataType attributes can't be used to validate user input. They only provide hints for rendering values using templated helpers.

    If there is not a built in validation attribute for what you need, eg, Range or Required, then what you should do is to create a custom property validation attribute and decorate your model property with that for the purposes of validation. EG, for DataType.EmailAddress

    This is described in Pro Asp.net mvc 3 Framework (Adam Freeman and Steve Sanderson, page 618 or thereabouts)