Click here to Skip to main content
15,887,822 members
Articles / Entity Framework
Tip/Trick

Data validation framework at entity level using Data Annotations

Rate me:
Please Sign up or sign in to vote.
4.86/5 (10 votes)
11 Nov 2013CPOL 34.3K   13   5
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. C#
    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. C#
    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. C#
    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. C#
    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. C#
    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)


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

Comments and Discussions

 
Suggestionstatic or cache validationContext ? Pin
Dick Baker3-Apr-15 0:14
Dick Baker3-Apr-15 0:14 
QuestionAwesome Article Pin
Member 1156707430-Mar-15 4:15
Member 1156707430-Mar-15 4:15 
QuestionHow to use a custom validation in the class? Pin
sukeshchand30-Jun-14 1:33
professionalsukeshchand30-Jun-14 1:33 
AnswerRe: How to use a custom validation in the class? Pin
sathya885-Jul-14 21:14
professionalsathya885-Jul-14 21:14 
GeneralRe: How to use a custom validation in the class? Pin
sukeshchand6-Jul-14 20:18
professionalsukeshchand6-Jul-14 20: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.