2

I am having a datetime input field and I want to asure user enters a date atleast 24 hours later than Datetime.Now. I tried this:

    [Range(typeof(DateTime), DateTime.Now.ToString(), DateTime.Now.AddDays(1).ToString())]
    public DateTime EndDate { get; set; }

But I am getting compiler error because values must be a constants. So what should I do?

user2412672
  • 1,459
  • 3
  • 20
  • 36

2 Answers2

3

What you need is a custom validation attribute so that you can do your comparison:

[CustomValidation(typeof (Validator), "ValidateEndTimeRange")]
public DateTime EndDate { get; set; }

And then your actual validator:

namespace MyMVCApp
{
    public class Validator
    {
        public static ValidationResult ValidateEndTimeRange(DateTime endTime)
        {

            if(endTime.EndDate < DateTime.Now || endTime.EndDate > DateTime.Now.AddDays(1)){
                return new ValidationResult("Your end date is outside of the acceptable range.");
            }

            return ValidationResult.Success;
        }
    }
}
siva.k
  • 1,344
  • 14
  • 24
0

Here's some JQuery code where I am getting the weeks between two date fields. Input is in this format 01/01/1990. It's not exactly what you need but it could get you started if you want to validate client side.

var startDate = $("#startDate").val();
        var endDate = $("#endDate").val();

        var startDateSplit = startDate.split("/");
        var endDateSplit = endDate.split("/");

        var stDate = new Date(startDateSplit[2], (startDateSplit[0] - (1)), startDateSplit[1]);
        var enDate = new Date(endDateSplit[2], (endDateSplit[0] - (1)), endDateSplit[1]);


        var startMonth = parseInt(startDateSplit[0]);
        var endMonth = parseInt(endDateSplit[0]);


        var daysBetween = (enDate.getTime() - (stDate.getTime())) / (1000 * 60 * 60 * 24); // time in days
        var weeksBetween = Math.ceil(daysBetween / 7);
CSharper
  • 5,420
  • 6
  • 28
  • 54