C# Data Annotations

Posted by in C# category on for Intermediate level | Points: 250 | Views : 19440 red flag
Rating: 5 out of 5  
 1 vote(s)

This article explains C# Data Annotations, how to implement them in the class and extract errors.


Validations is one of the most important things for any application. Developers tend to write long if/else conditions for implementing validation logic. Now this not only makes the code complex but also we can have defective code if the logic is not tested.

By using Data annotations you do not need to write lot of code. You can think data annotation as reusable validation library. They are ready made attributes which you can decorate on your business class / model and your validations are done.

Implementation of Data Annotations:

Implementing data annotation is a two-step process. First you need to decorate your class properties with the data annotation validator attributes. Below is a simple class which has “Required” and “StringLength” attributes.

To get the below attributes you need to import “System.ComponentModel.DataAnnotations” namespace.

public class Customer   //Creation of Class Customer
[Required]		// Required Field
public int Id { get; set; }

[Required(ErrorMessage="Please Enter Customer Name")] // Required Field
[StringLength(9)]		//Maximum Length of Name should be 9
public string Name { get; set; }

[Required(ErrorMessage = "Please Enter Customer Address")] // Required    
public string Address { get; set; }

And in the next step we will use the validation context and the validator class to check for validation errors.

So first create the object which has the data annotation attribute decorated and fill it with data. You can see in the below code I have specified “Name” and “Address” value as empty. In those two properties we had decorated “Required” data annotation attribute( refer the previous code).

If you are expecting that validation will fire right now, you are wrong. Data annotations are just attributes or in other words they are mere meta-data. They themselves do not do anything. Over these data annotation a.k.a meta-data we need to run the validator class to check for the objects validations.

Customer cus = new Customer(); //Object created
cus.Id = 12;			
cus.Name = "";
cus.Address = "";

So you can see in the below code we have created the “ValidationContext” and we have ran the “Validator.TryValidateObject” method which will check your objects data against the decorated data annotation attribute.

Once the “Validator.TryValidateObject” method runs over the object it will fill the errors in the errors collection.

var context = new ValidationContext(cus, null, null); //Context
var result = new List();	   //ValidationResult
bool IsValid = Validator.TryValidateObject(cus,context,result,true);
foreach(var msg in result)
Console.WriteLine(msg.ErrorMessage); //Printing the Error Messages

Some other Data Annotations which I feel very useful:

  • DisplayName – Defines the text we want used on form fields and validation messages
  • Range – Gives a maximum and minimum value for a numeric field
  • Bind – Lists fields to exclude or include when binding parameter or form values to model properties
  • ScaffoldColumn – Allows hiding fields from editor forms
  • RegularExpressions – Only allow a particular pattern

In case you want to see C# data annotation in action, please see the below youtube video where data annotation is actually demonstrated.

Page copy protected against web site content infringement by Copyscape

Login to vote for this post.

Comments or Responses

Posted by: Poster on: 12/15/2015 | Points: 25
Good video explanations by Questpond on C# Data Annotations.

Do keep publishing.
Posted by: Rajeshatkiit on: 12/16/2015 | Points: 25
Good article.
Providing this link for more info.
Posted by: Rajayadav on: 12/24/2015 | Points: 25
Nice, Thanks for sharing
Posted by: Stonemaddox on: 12/28/2017 | Points: 25
Yeah, I agree, video explanations are quite good.

Login to post response

Comment using Facebook(Author doesn't get notification)