I wrote a function to check if a date is valid
I wrote all except one small part
The function does not work and I cannot find the error, can you kindly help?
I can see that because the number 29 is not in the array it's not working however am confuddled how to get it to work
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
}
*/
<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>