ASP.NET Core Web API - DateTime Data Annotations Compare dates?

Cenk 1,036 Reputation points
2022-12-30T13:53:53.96+00:00

Hello,

When the request is made, is there a way to compare with data annotations if the start date is smaller than the end date?

Thank you.

public class OrderHistoryRequestDto  
    {  
        [Required(ErrorMessage = "Please add StartDate to the request.")]  
        [DataType(DataType.Date)]  
        public DateTime? StartDate { get; set; }  
        [Required(ErrorMessage = "Please add EndDate to the request.")]  
        [DataType(DataType.Date)]  
        public DateTime? EndDate { get; set; }  
    }  
Developer technologies .NET Entity Framework Core
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2022-12-30T14:55:00.453+00:00

    Write custom validation.

        public class OrderHistoryRequestDto : IValidatableObject  
        {  
            [Required(ErrorMessage = "Please add StartDate to the request.")]  
            [DataType(DataType.Date)]  
            public DateTime? StartDate { get; set; }  
            [Required(ErrorMessage = "Please add EndDate to the request.")]  
            [DataType(DataType.Date)]  
            public DateTime? EndDate { get; set; }  
      
            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)  
            {  
                if(EndDate.Value <= StartDate.Value)  
                {  
                    yield return new ValidationResult("End date must be greater than the start date.", new[] { "EndDate" });  
                }  
            }  
        }  
      
    

    If you want an attribute then write a custom attribute.

    There is also the openly published documentation which you can read to figure out if an existing attribute will suit your needs. For example, the compare attribute.

    Model validation in ASP.NET Core MVC and Razor Pages

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.