开发者

How to Prevent Date Objects from Wrapping in IE

开发者 https://www.devze.com 2023-02-15 01:41 出处:网络
I am writing a form validator that needs to combine the values of three fields/drop downs into a string and check that string to see if it is a valid date. Currently, I am doing this by combining the

I am writing a form validator that needs to combine the values of three fields/drop downs into a string and check that string to see if it is a valid date. Currently, I am doing this by combining the values into a string of the form mm/dd/yyyy and running that string through a comparison:

// Value is a string like mm/dd/yyyy
var date = new Date(value);
if( !date_regex.test(value) || date.toString() == 'Invalid Date' ) {
    errors[element] = "Please provide a valid date";
}

This works fine in almost every case. In IE8, if the string is formed such that the month or day exceed the allowance for the given component, the date wraps them instead of marking the date as invalid. Examples:

string: 03//2011
should be valid: no
is valid: no
Date.toString(): Invalid Date
correct: yes

string: 03/10/2011
should be valid: yes
is valid: yes
Date.toString(): Wed Mar 10 00:00:00 PST 2010
correct: yes

string: 03/40/2011
should be valid: no
is valid: yes
Date.toString(): Fri Apr 9 00:00:00 PST 2010
correct: no

string: 20/05/2011
should be valid: no
is valid: yes
Date.toString开发者_如何学编程(): Fri Aug 5 00:00:00 PST 2010
correct: no

I've tried using Date.parse(value) and checking for NaN, but the date wraps the timestamp, too.

Any ideas on how to get IE to behave like the others?

Thanks much


Convert the date object back into a string (by querying for the month,day,and year). If it matches what the user typed, then it's likely valid.

var year, month, day, compareString;

var date = new Date(value);

if( !date_regex.test(value) || date.toString() == 'Invalid Date' ) {
    errors[element] = "Please provide a valid date";
}
else {

    year = date.getFullYear().toString();

    month = (date.getMonth() >= 10) ? (date.getMonth().toString()) : ("0" + date.GetMonth().toString());

    day = (date.getMonth() >= 10) ? (date.getDate().toString()) : ("0" + date.GetDate().toString());

    compareString = month + "/" + day + "/" + year;

    if (compareString != value) // where "value" is what the user typed
        errors[element] = "Please provide a valid date";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消