Tuesday, February 23, 2016

Custom Validation in MVC/Web API using ValidationAttribute

This article is to help us, how to implement custom validation and use it as Data Annotation.
Custom Validation is very useful when we are using the same Property in number of places in our application, rather than to add AddModelError in ModelState, it is a good practice to create this in a separate reusable library so that we can use this in project with very consistent way and re-use in any other project. This should be project independent library and reusable component. 
Following are the steps to create Custom Validator and use it in view model classes.

  1. Create New class DateRangeAttribute inherit from ValidationAttribute
  2. Ensure value is of type DateTime, if not throw ValidationException.
  3. Create constructor to get values dynamically from the View Model.
  4. Override IsValid method of ValidationAttribute class and write logic to validate Date range.
Example
Date Range Attribute Class
 public class DateRangeAttribute: ValidationAttribute
    {
        private int _endAge;
        private int _startAge;

        public DateRangeAttribute(int startAge, int endAge)
        {
            startAge = _startAge;
            endAge = _endAge;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if(!(value is DateTime))
            {
                throw new ValidationException("DateRange is valid for DateTime property only.");
            }
            else
            {
                var date = (DateTime)value;
                //Better to create DateTime extension method to calculate Age
                if ((Calculate.GetAge(date)< _startAge) || (Calculate.GetAge(date) < _endAge))
                {
                    return new ValidationResult(this.FormatErrorMessage(validationContext.MemberName));
                }
                else
                {
                    return ValidationResult.Success;
                }
            }
        }

    }
Usage
    public class User
    {
        [Required]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        [DateRange(18, 100)]
        public string BirthDate { get; set; }


    }

3 comments:

Git Commands and Using Them in Visual Studio

 Git is a widely used version control system that allows developers to manage changes to their code and collaborate with other IDE like Visu...