Click here to Skip to main content
12,754,391 members (30,573 online)
Click here to Skip to main content
Add your own
alternative version


11 bookmarked
Posted 9 Nov 2013

Data validation framework at entity level using Data Annotations

, 11 Nov 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
A simple framework for data validation using data annotations at entity level.


This article is all about creating a simple data validation framework on entities using Data Annotation.


Leave aside the business rule validation for a while, ever wondered on how to do data validation with the help of Data Annotations at the entity level? Here is a simple framework to achieve what we are thinking of now ;-)

Using the code

Let us split this whole concept into five small parts:

  1. Create a generic entity class and inherit it in all the classes on which we wish to do data validation.
  2. public abstract class Entity
        public virtual int Key { get; set; }
    public class UserAccount : Entity
        public virtual string Email { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
            ErrorMessage = "Personal phone format is not valid.")]
        public virtual string PersonalPhone { get; set; }
  3. Create an EntityValidation class which does the actual validation:
  4. public class EntityValidation<T> where T : Entity
        public IEnumerable<ValidationResult> Validate(T entity)
            var validationResults = new List<ValidationResult>();
            var validationContext = new ValidationContext(entity, null, null);
            Validator.TryValidateObject(entity,validationContext, validationResults, true);
            return validationResults;
  5. Create an EntityValidator class which acts as the entry point to use this framework (which in turn uses EntityValidation).
  6. public class EntityValidator
        public static IEnumerable<ValidationResult> ValidateEntity<T>(T entity) where T:Entity
            return new EntityValidation<T>().Validate(entity);
  7. Use this framework inside the Entity class (that was created in Step-1)
  8. public abstract class Entity
        public virtual int Key { get; set; }
     	public virtual IEnumerable<ValidationResult> Validate()
            return EntityValidator.ValidateEntity(this);
  9. It's time to start using this framework in all our entities (which are derived from Entity):
  10. class Program
        static void Main(string[] args)
            var student = new UserAccount() 
            { Email = "", FirstName = "fn123", 
              LastName = "ln123", PersonalPhone = "1234" };
            foreach (var error in student.Validate())

The errors would look like this:

errors = Count = 4
[0] = {The Email field is not a valid e-mail address.}
[1] = {The field FirstName must be a string with a maximum length of 2.}
[2] = {The field LastName must be a string with a maximum length of 2.}
[3] = {Personal phone format is not valid.}

Points of Interest

If you would like to know more about Data Annotations, please refer the following MSDN link:

(This is my first technical article. Please do post your comments to help me improve more.)


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


About the Author

Software Developer
India India
A passionate developer with a hunger to learn more Smile | :)

You may also be interested in...


Comments and Discussions

Suggestionstatic or cache validationContext ? Pin
Dick Baker3-Apr-15 1:14
memberDick Baker3-Apr-15 1:14 
QuestionAwesome Article Pin
Member 1156707430-Mar-15 5:15
memberMember 1156707430-Mar-15 5:15 
QuestionHow to use a custom validation in the class? Pin
sukeshchand30-Jun-14 2:33
professionalsukeshchand30-Jun-14 2:33 
AnswerRe: How to use a custom validation in the class? Pin
sathya885-Jul-14 22:14
professionalsathya885-Jul-14 22:14 
GeneralRe: How to use a custom validation in the class? Pin
sukeshchand6-Jul-14 21:18
professionalsukeshchand6-Jul-14 21:18 

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
Web02 | 2.8.170217.1 | Last Updated 11 Nov 2013
Article Copyright 2013 by sathya88
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid