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.

using System.ComponentModel.DataAnnotations;

namespace Contacts.Models
    public class Contact
        [StringLength(50, MinimumLength = 4)]
        public string Name { get; set; }
        public string State { get; set; }
        [Display(Name = "Zip Code")]
        public string ZipCode { get; set; }

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.

private void ValidationExample()
    var contact = new Contact { Name = "Bob", State = "TN" };

    var context = new ValidationContext(contact);
    var errors = new List<ValidationResult>();

    if (!Validator.TryValidateObject(contact, context, errors))
        foreach (ValidationResult result in errors)
            //act on error

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.

7 thoughts on “Data Annotations”

  1. Hi,

    The example seems to be straightforward, but I can’t include DataAnnotations namespace in winforms class (System.ComponentModel does NOT contains it in winforms). How did you get it working?

    1. Not sure what the issue is. I have been using DataAnnotations in a winforms application. Do you have a sample app you could throw on Github and I can see if I can help?

        1. If you add the following line to your JDE_Scanner_Desktop.csproj after <Reference Include="System" /> and reload the project it should work for you.

          <Reference Include="System.ComponentModel.DataAnnotations" />

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.