MVC model validation for date

There is no need to disable jQuery date validation (and that is likely to cause other issues). You just need to override the range method of the $.validator.

By default, it works with numeric values (and then falls back to a string comparison), so you can add the following script (after jquery.validate.js and jquery.validate.unobtrusive.js, but not wrapped in $(document).ready

$.validator.methods.range = function(value, element, param) {
    if ($(element).attr('data-val-date')) {
        var min = $(element).attr('data-val-range-min');
        var max = $(element).attr('data-val-range-max');
        var date = new Date(value).getTime();
        var minDate = new Date(min).getTime();
        var maxDate = new Date(max).getTime();
        return this.optional(element) || (date >= minDate && date <= maxDate);
    }
    // use the default method
    return this.optional( element ) || ( value >= param[ 0 ] && value <= param[ 1 ] );
};

Then you can use the RangeAttribute on your property

[Range(typeof(DateTime), "1/1/1966", "1/1/2020")]
public DateTime Date { get; set; }

Leave a Comment