问题描述
令人沮丧的是,赋值后变量始终是未定义的。 请在这里解释我做错了什么。
$(document).ready(function() {
$("#submitButton").click(function() {
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
if (!isDate(startDate) && !isDate(endDate))
{
alert ('Start Date and End Date is invalid');
return false;
}
... other condition removed for clarity
});
});
function isDate(dateText)
{
var comp = [];
var comp2 = '';
var y_length = 0;
comp = dateText.split('/');
comp2 = comp[2];
y_length = comp2.length;
//invalid if year length is less than or greater than 4
if (y_length < 4 || y_length > 4) {
return false;
}
var m = parseInt(comp[0], 10);
var d = parseInt(comp[1], 10);
var y = parseInt(comp[2], 10);
var date = new Date(y, m - 1, d);
if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
return true;
} else {
return false;
}
}
我amg在y_length赋值行上得到“ 无法读取未定义的属性长度 ”,此行:
//comp2 here is undefined
y_length = comp2.length;
此外,您对使用JavaScript进行日期验证有什么建议吗? 谢谢。
1楼
如果dateText中至少不包含/的2个实例,则分割后最终将少于3个元素,因此
comp2 = comp[2];
将comp2设置为undefined,
y_length = comp2.length;
会出错。 如果输入的dateText中包含2个(或更多实例)/,则不应出现此错误。 如果是这样,您将要检查dateText的值(带有警报或console.log)
您可能想要做类似的事情
if (comp.length > 2) {
comp2 = comp[2];
...
else {
// error handling
...