Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Validations using C# DataAnnotation

4.18/5 (7 votes)
11 May 2015CPOL2 min read 39.5K  
In this short article, we will discuss how C# DataAnnotation library helps us to do validations.

Table of Contents

Introduction

Validations are one of the most important aspects of any software application. Normally as a best practice, we put these validations in the business class, model, etc. So if you normally see the trend, developers end up writing these validations in the “set” method of the class property.

C#
public class Customer
    {
        private string _CustomerName;
        public string CustomerName
        {
            get { return _CustomerName; }
            set 
            {
                if (value.Length == 0)
                {
                    throw new Exception("Customer Name is required");
                }
                _CustomerName = value; 
            }
        }    
    }

DataAnnotation” gives you readymade attributes which you can decorate on the class properties and the validation will be applied accordingly.

C#
[Required]
public string CustomerName
{
            get { return _CustomerName; }
            set {_CustomerName = value; }
}

How to use “DataAnnotations” ?

Step 1: Refer System.ComponentModel.DataAnnotations

The first step is to add reference to “System.ComponentModel.DataAnnotations” assembly to your class library project.

Step 2: Decorate the class with attributes

The next step is to decorate the class with validation attributes. For instance, on the “CustomerName” property, we have decorated the “Required” attribute.

C#
public class Customer
{
        private string _CustomerName;

        [Required]
        public string CustomerName
        {
            get { return _CustomerName; }
            set {_CustomerName = value; }
        }
}

Step 3: Call the “Validator” for validation

Once the validation attributes are decorated, we need to call the “Validator” class to do the validations. Create the customer object and set the “CustomerName” property to nothing, so validation errors fire up.

C#
Customer obj = new Customer();
obj.CustomerName = "";

Use the above created object to create the “ValidationContext” object.

C#
var context = new ValidationContext(obj,null,null);

Use “Validator” to call “TryValidateObject” method to run the validations. The validation errors get collected in the “ValidationResult” collection.

C#
var result = new List<validationresult>(); var isValid = Validator.TryValidateObject(obj, context, result,true); </validationresult>

If you wish to loop through the error results, you can run a “foreach” on the “result” collection.

C#
foreach (var str in result)
{
Console.WriteLine(str.ErrorMessage.ToString());
}

Below is a pictorial representation of the above code. In simple words, the object to be validated is passed to the “validator” class with the context and the error results come out in “ValidationResult” collection.

Image 1

FYI: If you have multiple validation, do not forget to make the last property true.

C#
var isValid = Validator.TryValidateObject(obj, context, result,true);

Also, see the following video on C# annotations:

Image 2

For Further reading do watch  the below interview preparation videos and step by step video series.

License

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