Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Basic Introduction to Data Annotation in .NET Framework

4.93/5 (29 votes)
6 Oct 2014CPOL3 min read 111.2K   391  
Basic introduction to Data Annotation in .NET Framework

Introduction

Data Annotation in .NET Framework means add extra meaning to the data by adding attribute tags. The advantage of using Data Annotation feature is that by applying Data Attributes, we can manage the data definition in a single place and do not need re-write the same rules in multiple places.

The Data Annotation feature got introduced in .NET 3.5 and the System.ComponentModel.DataAnnotations namespace contains the classes that are used as data attributes.

The Data Annotation attributes falls into three categories:

  1. Validation Attributes: Used to enforce validation rules.
  2. Display Attributes: Used to specify how data from a class /member is displayed in the UI.
  3. Modelling Attributes: Used to specify the intended use of class member and the relationship between classes.

Here in this article, I will be walking through the basic steps involved in implementing the Data Annotation feature. I am using Visual Studio Express 2013 for Desktop as my development environment targeting .NET framework 4.5.

First we will be creating our Data class, let's call it Employee. The requirement says Employee class should have properties like Name, Age, Email and Phone Number with the below criteria.

  • Name cannot be blank and should be of 3 characters minimum and 100 maximum characters.
  • Age should be between 18 and 99.
  • Email and Phone number should hold the respective data type validations.

Note: This is only a sample intended to demonstrate the .NET Data Annotation feature. I will be using some of the basic Data Annotation attributes and for more details on data annotation attribute, please refer to the Data Annotation documentation.

To implement the above requirement, we need to code in the UI layer to accommodate/validate the above criteria. The disadvantage is that if are using the Employee class in multiple places, we need to re-write the validation logic creating duplicate code which is not a good practice.

Here comes the beauty of .NET Data Annotation feature. We add Data Annotation attributes to the Employee class properties and the .NET framework takes care of the validation/display for us. We can add custom error messages as part of Data Annotation attribute.

Step 1

Create an empty solution as below. This will help us to add more Projects later.

Image 1

Step 2

Next create a class library project to hold Employee class as below to the solution.

Image 2

Add a class named Employee.cs and add reference to System.ComponentModel.DataAnnotations assembly to utilize the Data Annotation feature as below:

Image 3

Step 3

To allow the usage of types in System.ComponentModel.DataAnnotations, add the below code to Employee.cs.

C#
using System.ComponentModel.DataAnnotations;

Image 4

Step 4

Add the below properties to the Employee class with the respective Data Annotation attributes.

C#
public class Employee
    {
        [Required (ErrorMessage="Employee {0} is required")]
        [StringLength (100,MinimumLength=3,
        ErrorMessage="Name Should be minimum 3 characters and a maximum of 100 characters")]
        [DataType(DataType.Text)]
        public string Name { get; set; }

        [Range(18,99, ErrorMessage="Age should be between 18 and 99")]
        public int Age { get; set; }

        [DataType(DataType.PhoneNumber)]
        [Phone]
        Public string PhoneNumber { get; set; }

        [DataType(DataType.EmailAddress)]
        [EmailAddress]
        Public string Email { get; set; }
    }

Image 5

Step 5

Testing the Employee class Data Validation using a Console Application.

Create a new Console Application project and add reference to Employee class library and System.ComponentModel.DataAnnotations assembly.

Our Solution explorer looks as below:

Image 6

Step 6

To allow the usage of types in System.ComponentModel.DataAnnotations and Employee class, add the below code to Program.cs:

C#
using Model.Employee;
using System.ComponentModel.DataAnnotations;

namespace TestEmployeeValidation
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Employee class Validation");
            Console.WriteLine("---------------------------\n");

            Employee objEmployee = new Employee ();
            objEmployee.Name = "sa";
            objEmployee.Age = 12;
            objEmployee.PhoneNumber = "1234as";
            objEmployee.Email = "test@re";

            ValidationContext context = new ValidationContext(objEmployee, null, null);
            List<ValidationResult> results = new List<ValidationResult>();
            bool valid = Validator.TryValidateObject(objEmployee, context, results, true);

            if (!valid)
            {
                foreach (ValidationResult vr in results)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.Write("Member Name :{0}", vr.MemberNames.First());
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("   ::  {0}{1}", vr.ErrorMessage, Environment.NewLine);
                }
            }

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("\nPress any key to exit");
            Console.ReadKey();
        }
    }
}

Hit F5 (or whatever you have configured your debug key in Visual Studio) to validate Employee class.

Now, we can see the validation details as below in the Console Window displaying Validation errors based on the Data Annotation attributes added to Employee class.

Image 7

Here, the advantage of using Data Annotation attributes is that now if we want to reuse the Employee class in an ASP.NET MVC application or Windows Forms Application, we can still use the same validation without writing any extra piece of Validation code.

This is just a beginner article on how to use .NET Data Annotation. Please refer to the Data Annotation documentation for more details on Data Annotation attribute and its capabilities.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)