Using Data Annotation Attributes

Microsoft Enterprise Library 5.0

DropDown image DropDownHover image Collapse image Expand image CollapseAll image ExpandAll image Copy image CopyHover image

The System.ComponentModel.DataAnnotations namespace in the .NET Framework contains a series of attributes that you can add to your classes and class members to signify metadata for these classes and members. They include a range of validation attributes that you can use to apply validation rules to your classes, in much the same way as you can with the Validation block attributes. For example, the following shows how you can use the Range attribute to specify that the value of the property named OnOrder must be between 0 and 50.

C# Copy Code
[Range(0, 50, ErrorMessage = "Quantity on order must be between 0 and 50.")]
public int OnOrder { get; set; } 
Visual Basic Copy Code
<Range(0, 50, ErrorMessage:="Quantity on order must be between 0 and 50.")> _
Public Property OnOrder() As Integer
End Property

Compared to the validation attributes provided with the Validation block, there are some limitations when using the validation attributes from the DataAnnotations namespace:

  • The range of supported validation operations is less comprehensive, though there are some new validation types available in version 4.0 of the .NET Framework that extend the range. However, some validation operations such as property value comparison, enumeration membership checking, and relative date and time comparison are not available when using data annotation validation attributes.
  • There is no capability to use Or composition, as there is with the Or composite validator in the Validation Application Block. The only composition available with data annotation validation attributes is the And operation.
  • You cannot specify rule sets names, and so all rules implemented with data annotation validation attributes belong to the default rule set. You will see more details about rule sets later in this chapter.
  • There is no simple built-in support self-validation, as there is in the Validation block.
Data Annotation validators can only be applied to properties.

You can, of course, include both data annotation and Validation block attributes in the same class if you wish, and implement Self validation using the Validation block mechanism in a class that contains data annotation validation attributes. The validation methods in the Validation block will process both types of attributes.

For more information about data annotations, see System.ComponentModel.DataAnnotations Namespace (.NET Framework version 3.5) and System.ComponentModel.DataAnnotations Namespace (.NET Framework version 4.0).