我写了一个函数来检查日期是否有效
我写了除了一小部分之外的所有内容
该功能不起作用,我找不到错误,你能帮忙吗?
我可以看到,因为数字29不在数组中,它不能正常工作但是我很困惑如何让它工作
function isValidDate() {
var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[-](0?[1-9]|1[012])[-]\d{4}$/;
var readDate = document.getElementById("myDate").value;
if (readDate.length <= 10) {
<!--debug-->
//console.log(readDate);
/* split date into DD-MM-YYYY format */
var splitDate = readDate.split('-');
var day = splitDate[0];
var month = splitDate[1];
var year = splitDate[2];
/* DEBUG - print split date into DD-MM-YYYY format */
console.log('day ' + day);
console.log('month ' + month);
console.log('year ' + year);
// Create list of days of a month [assume there is no leap year by default]
var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
//if month is between 1-12
if (month == 1 || month < 13) {
//check for invalid month
if (month == 00) {
console.log('0 - Invalid MONTH format!');
return 0;
}
//check for invalid day
if (day == 00) {
console.log('0 - Invalid DAY format!');
return 0;
}
//check DAY exists in the MONTH
if (day > ListofDays[month - 1]) {
console.log('1 - Invalid DATE format!');
return 0;
} else {
console.log('1 - Valid DATE format!');
return 1
}
} else {
console.log("Invalid MONTH");
return 0;
}
//check for leap year
if (year % 4 === 0 && year % 100 !== 0) {
console.log('The year ' + year + ' is a leap year.');
return 1;
} else if (year % 4 === 0 && year % 100 === 0 && year % 400 === 0) {
console.log('The year ' + year + ' is a leap year.');
return 1;
} else {
console.log('The year ' + year + ' is NOT a leap year');
return 0;
}
} else {
console.log("Invalid DATE length")
}
}
/* This is the only bit I did not write:
if (day > ListofDays[month-1])
{
console.log('1 - Invalid DATE format!');
return 0;
}
else
{
console.log('1 - Valid DATE format!');
return 1
}
*/
&#13;
<p>Input a date and check it's in a)correct format and b)it is a valid date</p>
<input type="text" id="myDate" placeholder="DD-MM-YYYY"> <br><br>
<button type="button" onclick="isValidDate()"> Check Date </button>
&#13;
答案 0 :(得分:1)
这是一个让代码尽可能接近您想要的代码的解决方案。使用我在评论中已经建议的日期对象的简单解决方案已由其他人详细阐述
function showError(str) {
console.log(str)
return false;
}
function isValidDate() {
var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[-](0?[1-9]|1[012])[-]\d{4}$/;
var readDate = document.getElementById("myDate").value;
if (readDate.length != 10) return showError("Invalid DATE length") // not correct length
console.log(dateformat.test(readDate));
if (!dateformat.test(readDate)) {
return showError("Invalid DATE format") // not matching regex
}
/* split date into DD-MM-YYYY format */
var splitDate = readDate.split('-');
var day = splitDate[0];
var month = splitDate[1];
var year = splitDate[2];
/* DEBUG - print split date into DD-MM-YYYY format */
console.log('day ' + day);
console.log('month ' + month);
console.log('year ' + year);
// Create list of days of a month [assume there is no leap year by default]
var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
//if month is not between 1-12
if (month <= 0 || month > 12) {
return showError('0 - Invalid MONTH format!');
}
var isLeap = false;
//check for leap year
if (year % 4 === 0 && year % 100 !== 0) {
console.log('The year ' + year + ' is a leap year.');
isLeap = true;
} else if (year % 4 === 0 && year % 100 === 0 && year % 400 === 0) {
console.log('The year ' + year + ' is a leap year.');
isLeap = true;
} else {
console.log('The year ' + year + ' is NOT a leap year');
}
//check DAY exists in the MONTH
var testDay = ListofDays[month - 1]; // array starts at 0
// testDay += isLeap ? 1 : 0; // add one to testDay using ternary operator
if (isLeap) testDay++; // less code, does the same as above
if (day > testDay) {
return showError('1 - Invalid DATE format!');
}
console.log('1 - Valid DATE format!');
// You can return true here if you want
}
&#13;
<p>Input a date and check it's in a)correct format and b)it is a valid date</p>
<input type="text" id="myDate" placeholder="DD-MM-YYYY"> <br><br>
<button type="button" onclick="isValidDate()"> Check Date </button>
&#13;
答案 1 :(得分:0)
放弃所有这些。
<input type="date" />
完成工作。
或者,由于您要指定格式,您可以执行以下操作:
var input = document.getElementById("myDate").value;
var parts = input.split("-");
var date = new Date(parts[2],parts[1]-1,parts[0]);
return date.getFullYear() == parts[2]
&& date.getMonth() == parts[1]-1
&& date.getDate() == parts[0];
这是有效的,因为如果日期超出有效范围(例如,1月32日更正为2月1日),JavaScript将“修复”日期,因此只需检查它是否在收到日期时发生了任何变化。
答案 2 :(得分:0)
function validate(value) {
var v = false;
if (value) {
var r = value.match(/([0-9]{1,2}).?([0-9]{1,2}).?([0-9]{4})/);
if (r) {
var day1 = parseInt(r[1]);
var month1 = parseInt(r[2]);
var year1 = parseInt(r[3]);
var d = new Date(year1, month1 - 1, day1);
var day2 = d.getDate();
var month2 = d.getMonth() + 1;
var year2 = d.getFullYear();
v = day1 == day2 &&
month1 == month2 &&
year1 == year2;
}
}
return v;
}
<input type="text" id="toCheck" />
<button onclick="console.log(validate(document.getElementById('toCheck').value))">Check</button>
您可以尝试使用任何分隔符,这只是一个示例(我使用了一个技巧来检查实际日期)。您可以修改此功能以供个人使用。