Click here to Skip to main content
13,139,569 members (54,179 online)
Click here to Skip to main content
Add your own
alternative version

Stats

30K views
169 downloads
40 bookmarked
Posted 6 Oct 2014

Basic Introduction to Data Annotation in .NET Framework

, 6 Oct 2014
Rate this:
Please Sign up or sign in to vote.
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.

Step 2

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

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

Step 3

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

using System.ComponentModel.DataAnnotations;

Step 4

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

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; }
    }

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:

Step 6

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

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.

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)

Share

About the Author

Mathew Soji
Software Developer
India India
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionVery useful!!! Pin
Cheung Tat Ming12-Oct-14 6:32
memberCheung Tat Ming12-Oct-14 6:32 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun10-Oct-14 1:45
memberHumayun Kabir Mamun10-Oct-14 1:45 
QuestionGlobalization Pin
Member 32560317-Oct-14 2:08
memberMember 32560317-Oct-14 2:08 
AnswerRe: Globalization Pin
xondokan7-Oct-14 2:45
memberxondokan7-Oct-14 2:45 
GeneralRe: Globalization Pin
Member 32560317-Oct-14 3:00
memberMember 32560317-Oct-14 3:00 
GeneralRe: Globalization Pin
xondokan7-Oct-14 3:36
memberxondokan7-Oct-14 3:36 
GeneralRe: Globalization Pin
dmjm-h7-Oct-14 12:13
memberdmjm-h7-Oct-14 12:13 
AnswerRe: Globalization Pin
Mathew Soji7-Oct-14 3:38
memberMathew Soji7-Oct-14 3:38 
AnswerRe: Globalization Pin
Mathew Soji7-Oct-14 3:41
memberMathew Soji7-Oct-14 3:41 
AnswerRe: Globalization Pin
Mathew Soji16-Oct-14 1:08
memberMathew Soji16-Oct-14 1:08 
GeneralRe: Globalization Pin
Member 325603116-Oct-14 1:26
memberMember 325603116-Oct-14 1:26 
QuestionNice introduction to Data Annotation in .NET Framework Pin
Volynsky Alex6-Oct-14 10:41
professionalVolynsky Alex6-Oct-14 10:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170915.1 | Last Updated 6 Oct 2014
Article Copyright 2014 by Mathew Soji
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid