Data Annotations

Validation via data annotations in .NET is a great feature that is simple to implement. Here is an example model class that is using data annotations.

First step in using data annotations is to add a using statement for the System.ComponentModel.DataAnnotations namespace. This namespace allows you to add validation attributes to the properties that require validation and contains helper classes to run validate on attributed models.

In the example above Required, StringLength and Display are all validation attributes. For the most part the attributes are self-explanatory, but be aware most attributes also have options to give you more control of the validation. For example required attribute has an AllowEmptyStrings property that if set to true will allow an empty string to pass validation. String length is another example which has options for minimum and maximum lengths for the property being validated.

This is just a small sample of the built-in attributes that exist. Other built-in attributes range  from credit card and email address validation to file extension and range validation. If a built-in validation does not meet your needs then a custom attribute a can be created by deriving from ValidationAttribue.

MVC has a lot of great functionality built around data annotations. For instance as long as a client has JavaScript turned a form will not allow submission until the model passes all the validation conditions. On the server-side inside of a controller to run validation all it takes is to run ModelState.IsValid.

With winforms the story is not quite as simple, but still pretty straight forward. The following is a simple example of calling validation on a model.

Validator.TryValidateObject takes the model to be validated, a validation context (created with the model to validate) and an empty list of type ValidationResult. The function call returns false if any properties fail validation. In the example above the validation would fail since name only contains three characters the minimum length is set to four characters.

One thought on “Data Annotations”

Leave a Reply

Your email address will not be published. Required fields are marked *