2011-03-04 55 views
0

我正在寫一個表單驗證程序,它需要將三個字段/下拉列表的值組合到一個字符串中,並檢查該字符串以查看它是否爲有效日期。目前,我通過一個比較值組合成形式爲mm/dd/yyyy的字符串,然後運行該字符串這樣做:如何防止日期對象在IE中打包

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

這在幾乎所有情況下正常工作。在IE8中,如果字符串形成爲使得月份或日期超過給定組件的限額,則日期將對它們進行包裝,而不是將日期標記爲無效。例如:

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 

我試過使用Date.parse(值)和檢查NaN,但日期也包裝時間戳。

有關如何讓IE像其他人一樣行事的想法?

感謝很多

+0

[DateJS](http://www.datejs.com/)可能會有用。我沒有親自使用它。 – drudge 2011-03-04 19:28:29

回答

0

轉換日期對象返回到一個字符串(通過查詢,月,日和年)。如果它匹配用戶輸入的內容,那麼它可能是有效的。

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

好主意。像魅力一樣工作。謝謝! – ckoning 2011-03-04 20:02:11