65.9K
CodeProject is changing. Read more.
Home

Data validation framework at entity level using Data Annotations

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (10 votes)

Nov 10, 2013

CPOL
viewsIcon

34852

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

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