Click here to Skip to main content
15,883,809 members
Articles / Programming Languages / C#

Validations using C# "DataAnnotation"

Rate me:
Please Sign up or sign in to vote.
4.18/5 (7 votes)
11 May 2015CPOL2 min read 38.8K   26   4
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)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
SuggestionC# auto properties Pin
Member 1002736023-May-15 11:31
Member 1002736023-May-15 11:31 
QuestionNot a bad start. Pin
Pete O'Hanlon12-May-15 2:03
mvePete O'Hanlon12-May-15 2:03 
QuestionGood explanation Pin
Avadhesh Kumar Maurya11-May-15 23:43
Avadhesh Kumar Maurya11-May-15 23:43 

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.