JS中的日期函数,与设置的日期不起作用

时间:2014-08-24 15:13:10

标签: javascript asp.net validation

我必须验证并检查用户是否在ASP中未成年。因此,任何未满01/07/1998岁的人都是未成年人。我有3个下拉列表来选择日期,月份和年份。我正在使用JS。我尝试使用concat和split但他们不工作。任何人都可以帮忙吗?

function ValidateDate() {
    var dDay = document.getElementById('DateList');
    var dMonth = document.getElementById('MonthList');
    var dYear = document.getElementById('YearList');

    var day = dDay.selectedIndex;
    var month = dMonth.selectedIndex;
    var year = dYear.selectedIndex;

    var firstValue = year + month  + day;

    var setyear = "1998";
    var setmonth = "06";
    var setdate = "01";
    var secondValue = setyear + setmonth + setdate;

    var firstDate = new Date();
    firstDate.setFullYear(firstValue[0], (firstValue[1] - 1), firstValue[2]);

    var secondDate = new Date();
    secondDate.setFullYear(secondValue[0], (secondValue[1] - 1), secondValue[2]);

    if (firstDate > secondDate) {
        alert("Pass");
    }
    else {
        alert("Fail");
    }

}

 <asp:CustomValidator ID="CustomValidatorDate" runat="server" 
                        ErrorMessage=" You are underage" CssClass="error" Display="Dynamic" ClientValidationFunction="ValidateDate" ></asp:CustomValidator>

1 个答案:

答案 0 :(得分:1)

首先,您的日,月和年变量正在读取下拉列表的索引,而不是它们的值。

例如,您需要使用:

var day = dDay.value,
month = dMonth.value,
year = dYear.value;

然后将日期对象创建为

var firstDate = new Date(year, month, day);

-Dipen