2011-11-02 47 views
0

我正在使用移动网站,并且在月份,日期和年份有下拉框。如果他们选择过去的日期,我需要某些东西阻止他们继续下一步。我已经看到了这样做的日历控件,但我不想使用日历控件。我花了一天的更多时间寻找一些东西,但一直没有找到任何东西。有没有人有这样的事情,或知道可能我错过了什么?使用下拉框输入MM,DD和YYYY禁止使用JavaScript进行日期


function date_check() 
{ 
    var trans_date = document.form1.selectmonth.options[document.form1.selectmonth.selectedIndex].value + "-" + document.form1.selectday.options[document.form1.selectday.selectedIndex].value + "-" + document.form1.selectyear[document.form1.selectyear.selectedIndex].value; 
    var d = new Date(); 
    var today = (d.getMonth()+1) + "-" + d.getDate() + "-" + d.getFullYear(); 
    if(new Date(trans_date) < new Date(today)){ 
     alert("The shipping date cannot be in the past, please enter a valid shipping date."); 
     return false; 
     } 


} 

这是我想出了,但它不工作。我错过了别的吗?我会把它选为2011年1月1日,它不会提示警报。

回答

1

只需从相关元素中获取选定值,将值与“ - ”或“/”连接起来,然后使用构造函数创建日期对象 - 将其与当前日期进行比较 - 如果小于当前日期,然后失败。

// Inside your form's validation handler ... 

var year, month, day, provided_date, now = new Date(); 

// Remove the hours, minutes and seconds from the now timestamp 
now = new Date(now.getYear(), now.getMonth(), now.getDate()); 

// Get your year select - document.getElementById 
// or any other method you have available 

year = your_year_select.options[your_year_select.selectedIndex].value; 
// and so on for month and day 


// Remember, month is 0 indexed in JavaScript (January is month 0) 
// so make sure your dropdown values take account of this. 
// Otherwise, use month - 1 here. 
provided_date = new Date(year, month, day); 

// if all you need to do is validate the date 
return provided_date >= now; 
0

这听起来像你只需要一个验证功能,从选定的输入创建一个新的日期,并将其与当前日期进行比较。例如:

function isFutureDate(year, month, day) { 
    return (Date.parse("" + year + "-" + month + "-" + day)) - new Date() > 0; 
} 

除了您可能需要考虑时区转换。

相关问题