Date validator on DatePicker trigger false negatives in IE7/IE8

女生的网名这么多〃 提交于 2019-12-05 03:46:28

I think you're looking for the dateISO option:

$('form').validate({
    rules: {
        StartDate: {
            required: true,
            dateISO: true
        },
        EndDate: {
            required: true,
            dateISO: true
        }
    },
    messages: {
        StartDate: {
            required: "Start Date required",
            dateISO: "Invalid date. Must be formatted yyyy-mm-dd"
        },
        EndDate: {
            required: "End Date required",
            dateISO: "Invalid date. Must be formatted yyyy-mm-dd"
        }
    },
    submitHandler: function(form) {
        form.submit();
    }
});

IE won't parse dates in yyyy-mm-dd format, which is why using regular date fails in IE. I believe jQuery validate just uses Date.parse or new Date(dateString) to check for validity. To check this, try doing new Date("1987-11-14") and alerting the value in IE and FF. You'll get NaN in IE and a date object in FF.

Here's a working example: http://jsfiddle.net/andrewwhitaker/QqSrJ/2/

Example to overcome IE NaN

var startDate   = "1987-11-14";
startDate       = startDate.split("-");
startDate       = new Date(startDate[0], + startDate[1], startDate[2]);
alert(startDate);
Andrew Smith

Send the date how you need it formatted to a hidden field in your form using altField and altFormat, this fixed my NaN errors.

$("#selectorDate").datepicker({
    dateFormat: 'mm/dd/yy',
    altField: "#another_field_date",
    altFormat: "yy-mm-dd"
});

I had a problem in my own code, where the date format was the same as described above and the form in the JSP (with a little assistance from Spring's form tags) looked like this:

<fmt:formatDate pattern="yyyy-MM-dd" value="${user.dateOfBirth}" var="dob"/>
<form:input id="date-of-birth" type="date" path="dateOfBirth" value="${dob}"/>  

The problem was the the date field is optional (required=false in JQuery validation rules), but it used DatePicker, and was thus validated automatically when it was filled. The problem was that on all browsers, and on IE9 (and up) it validated correctly, but on IE8, it caused an "invalid date" validation stop.

I played with the jquery validation rules, I tried using dateISO (though I am by no means saying that this solution will not work for some), to no avail.

Turns out that in my case, all I had to do was remove the attribute 'type="date"'. Now the date validates properly, and remains an optional field.

In my case the class="date" attribute (not type="date") on the input field was causing validator to automatically add date validation to the field, which triggered the false negative in IE8. So I changed the class to 'date-select', then used the dateISO rule as in Andrew Whitaker's answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!