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

Cenk 956 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; }  
    }  
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,195 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,136 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