简体   繁体   中英

future dates raise error jquery ui datepicker

I have that script for jquery ui datepicker

var date = new Date(new Date().setDate(new Date().getDate() - 1));


$('.date').datepicker({
    dateFormat: 'dd-mm-yy',
    defaultDate: date,
    minDate: Date.parse("1900-01-01"),
    maxDate: Date.parse("2100-01-01"),
});

and in my view I have:

@Html.TextBoxFor(m => m.EndDate, new { @class = "date" })

It works ok for yesterday and previous dates, but raises error if i'll select today or higher date

在此输入图像描述

what's wrong?

EDIT

GOT IT It's about my format. I want it to be dd-mm-yy but when I select for example 15-05-2016 it says that there isn't 15 month in year. How can I solve that?

Date.parse() returns the number of milliseconds since January 1, 1970 for a date string, and minDate and maxDate can accept a number, but it is used in this way:

Number : A number of days from today. For example 2 represents two days from today and -1 represents yesterday

Therefore, the validation is expecting you to enter a date that is between 2208988800000 days in the past and 4102444800000 days in the future . These dates are incredibly distant, and are too large for a Date to handle.

To fix it, use new Date() instead.

$('.date').datepicker({
    dateFormat: 'dd-mm-yy',
    defaultDate: -1,
    minDate: new Date("1900-01-01"),
    maxDate: new Date("2100-01-01")
});

JSFiddle

I have not tried it myself, but it may solve this problem.

change above date format like this

dateFormat: 'mm-dd-yy',

or simply remove that line because default dateFormat is mm/dd/yy

As I get unobtrusive validation needs to be overloaded for different format this answer helped me.

$.validator.addMethod('date',
function (value, element) {
    if (this.optional(element)) {
        return true;
    }

    var ok = true;
    try {
        $.datepicker.parseDate('dd-mm-yy', value);
    }
    catch (err) {
        ok = false;
    }
    return ok;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM