Click here to Skip to main content
Click here to Skip to main content

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.

Introduction

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

Background

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 Wink | ;-)

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
    {
    	[Required]
        public virtual int Key { get; set; }
    }
    
    public class UserAccount : Entity
    {
        [Required]
        [StringLength(200)]
        [EmailAddress]
        public virtual string Email { get; set; }
    
        [Required]
        [StringLength(2)]
        public virtual string FirstName { get; set; }
    
        [Required]
        [StringLength(2)]
        public virtual string LastName { get; set; }
    
        [StringLength(20)]
        [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
    {
    	[Required]
        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 = "sasa.@gmai.com", FirstName = "fn123", 
              LastName = "ln123", PersonalPhone = "1234" };
            foreach (var error in student.Validate())
            {
                Console.WriteLine(error.ErrorMessage);
            }           
        }
    } 

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: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx.

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

License

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

Share

About the Author

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

Comments and Discussions

 
QuestionHow to use a custom validation in the class? Pinprofessionalsukeshchand30-Jun-14 2:33 
AnswerRe: How to use a custom validation in the class? [modified] Pinprofessionalsathya885-Jul-14 22:14 
GeneralRe: How to use a custom validation in the class? Pinprofessionalsukeshchand6-Jul-14 21:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411022.1 | Last Updated 11 Nov 2013
Article Copyright 2013 by sathya88
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid