Click here to Skip to main content
13,860,571 members
Click here to Skip to main content
Add your own
alternative version

Stats

22.4K views
26 bookmarked
Posted 11 May 2015
Licenced CPOL

Validations using C# "DataAnnotation"

, 11 May 2015
Rate this:
Please Sign up or sign in to vote.
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.

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.

[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.

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.

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

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

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.

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.

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.

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

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

Also, see the following video on C# annotations:

License

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

Share

About the Author


You may also be interested in...

Pro

Comments and Discussions

 
SuggestionC# auto properties Pin
Member 1002736023-May-15 12:31
memberMember 1002736023-May-15 12:31 
SuggestionMessage Closed Pin
12-May-15 10:51
memberA·syn·chro·nous12-May-15 10:51 
QuestionNot a bad start. Pin
Pete O'Hanlon12-May-15 3:03
protectorPete O'Hanlon12-May-15 3:03 
QuestionGood explanation Pin
Avadhesh Kumar Maurya12-May-15 0:43
memberAvadhesh Kumar Maurya12-May-15 0: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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190214.1 | Last Updated 11 May 2015
Article Copyright 2015 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid