Validation and Annotation

In ASP.NET MVC, two methods exist for validation: HTML helpers (i.e., field validator controls) and data annotation attributes.

Attributes from the System.ComponentModel.DataAnnotations namespace perform validation at the model level through attributes attached to properties. These attributes perform server-side validation and client-side. Many prefer attributes to HTML due to the simplicity of adding attributes to a property.


The System.ComponentModel.DataAnnotations namespace provides a set of attributes for validating property values of a model class. Some of the most important attributes applied to model classes follow:

  1. Required – It confirms the value assigned to a property.
  2. StringLength – It checks string length and also allows for the specification of extrema.
  3. Range – It confirms the value assigned to a property falls within a specified range.
  4. EmailAddress – It confirms a valid email has been submitted.
  5. RegularExpression – It confirms a match between the property value and the specified pattern.
  6. Url – It confirms a valid URL has been submitted.

All attributes include a default error message, and allow an error message to be specified. If the standard attributes fail to satisfy an application's needs, custom attributes can be created through inheriting a new validator attribute from a base attribute. The general syntax of an attribute follows:

[Attribute(parameters, Parameter = Value)]

The Data Annotations Model Binder must be downloaded to use annotation validators. Follow software documentation instructions for the particular needs of installation. Note that Microsoft offers no official support for the Model Binder.