MVC model validation for date

前端 未结 4 1825
别跟我提以往
别跟我提以往 2020-11-27 22:42

Is there any default validation for MVC 5 where I can set min and max value of date?

In my model i want date validation

    public class MyClass
             


        
4条回答
  •  醉酒成梦
    2020-11-27 23:13

    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; }
    

提交回复
热议问题