The System.ComponentModel.DataAnnotations namespace within
the .NET Framework includes a number of built-in validation attributes that you
can use. We’ve used 4 different ones in the sample above - [Required],
[StringLength], [Range], and [RegularExpression].
You can also optionally define your own custom validation
attributes and use them as well. You can define completely custom
attributes by deriving from the ValidationAttribute base class within the
System.ComponentModel.DataAnnotations namespace. Alternatively, you can
choose to derive from any of the existing validation attributes if you want to
simply extend their base functionality.
For example, to help clean up the code within our Person
class we might want to create a new [Email] validation attribute that
encapsulates the regular expression to check for valid emails. To do this
we can simply derive it from the RegularExpression base class like so, and call
the RegularExpression’s base constructor with the appropriate email regex:
We can then update our Person class to use our new [Email]
validation attribute in place of the previous regular expression we used before
– which makes the code more clean and encapsulated:
When creating custom validation attributes you can specify
validation logic that runs both on the server and on the client via JavaScript.
In addition to creating validation attributes that apply to
individual properties on an object, you can also apply validation attributes at
the class level – which allows you to perform validation logic across multiple
properties within an object. For an example of this in action, you can
review the “PropertiesMustMatchAttribute” custom attribute that is included in
the AccountModels.cs/vb file within the default ASP.NET MVC 2 application
project template (just do a File->New ASP.NET MVC 2 Web Project within VS
2010 and look for this class).