Creating Custom Validation using IValidatableObject (DataAnnotation) in ASP.NET MVC

.NET Framework provides a set of inbuilt data validation using DataAnnotation. 

But there might be cases where you might need to validate with your custom rules. Example of such case is like when you need to compare two values and one must be greater than (or less than another).

Here’s how you do it. 

You can change your Validate Function as per your need.
public class ViewModel: IValidatableObject
{
    [Required]
    public DateTime StartDate { get; set; }
    [Required]   
    public DateTime EndDate { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
       if (EndDate < StartDate)
       {
           return new ValidationResult(“EndDate must be greater than StartDate”);
       }
    }
}
Happy Coding!