2

I have created a datepicker using MVC5 DataType.Date:

[DataType(DataType.Date)]
public DateTime ArrivalDate { get; set; }

How can I set the minimum available date to Today and disable all past dates?

Alternatively, is there an option to disable a custom range of dates?

I have tried to create a custom DateRangeValidator using the this answer, but with that I get the following error: named parameter type constraints

Here's my Date range validator:

public DateTime FirstDate = DateTime.Today.Date;
    //public DateTime SecondDate { get; set; }

    protected override ValidationResult IsValid(DateTime date, ValidationContext validationContext)
    {
        // your validation logic
        if (date >= DbFunctions.TruncateTime(FirstDate))
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult("Date is not valid.");
        }
    }
Community
  • 1
  • 1
Forza
  • 1,619
  • 3
  • 28
  • 49

1 Answers1

3

Try building a custom validation attribute with your own logic :

        public sealed class PresentOrFutureDateAttribute: ValidationAttribute
        {
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {                 
                // your validation logic
                if (Convert.ToDateTime(value) >= DateTime.Today)
                {
                    return ValidationResult.Success;
                }
                else
                {
                    return new ValidationResult("Past date not allowed.");
                }
            }
        }
Guillaume
  • 12,824
  • 3
  • 40
  • 48
  • Why do you use an object for value? `Operator '>=' cannot be applied to operands of type 'object' and 'System.DateTime'` – Forza Mar 16 '15 at 16:29
  • It's an override so we must follow parent signature. Work on the object to cast/convert it to the expected type. – Guillaume Mar 16 '20 at 11:47