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.
ATTRIBUTES
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:
- Required – It confirms the value assigned to a property.
- StringLength – It checks string length and also allows for the specification of extrema.
- Range – It confirms the value assigned to a property falls within a specified range.
- EmailAddress – It confirms a valid email has been submitted.
- RegularExpression – It confirms a match between the property value and the specified pattern.
- 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.