I'm trying to write a method that checks whether a date is valid. It is passed in three Strings: month, day, and year, in order. Month should be from 0-11 instead of 1-12. I have tested the logic of the code in JavaScript and it works. is_int is another method that tests if a String is composed solely of numerical characters. Unfortunately, I am running into problems which I can't figure out.
function is_int(value) {
for (i = 0 ; i < value.length ; i++) {
if ((value.charAt(i) < '0') || (value.charAt(i) > '9')) return false
}
return true;
}
function isValidDate(value1:String, value2:String, value3:String)
{
if (!is_int(value3)) return false;
if (!is_int(value2)) return false;
if (!is_int(value1)) return false;
var v1 = parseInt(value1) + 1;
var v2 = parseInt(value2);
var v3 = parseInt(value3);
if (v1 > 12 || v1 < 1) return false;
if (v2 > 31 || v2 < 1) return false;
if (v2 == 31) if (v1 == 2 || v1 == 4 || v1 == 6 || v1 == 9 || v1 == 11) return false;
if (v1 != 2) return true;
if (v2 < 29) return true;
if (v2 == 30) return false;
if (v3 % 400 == 0)
return true;
else if (v3 % 100 == 0)
return false;
else if (v3 % 4 == 0)
return true;
else
return false;
}
My first tester is something that asks for three text inputs and, if the isValidDate function returns false, displays an alert. If not, it forwards to a blank html page. However, I tried this:
function validate() {
if (!isValidDate("a", "a", "a")) {
alert("wrong");
return false;
}
}
and the alert never displayed and it forwarded every time. Strangely enough, this still happened when I removed the exclamation point in front of isValidDate. I also tried swapping the double quotation marks for single, but that didn't fix the problem either. The same thing happens with my tester for is_int. I have no idea where I'm going wrong.
I know you didn't ask for it, but here's a much more valid way to check for dates, and it handles odd dates more consistently:
function isValidDate(year, month, day) {
var d = new Date(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10), 0, 0, 0);
return d.getFullYear() == year &&
(d.getMonth() + 1) == month &&
d.getDate() == day;
}
console.log(isValidDate("2011", "08", "04")); // true
console.log(isValidDate("bob", "08", "04")); // false
console.log(isValidDate("1979", "1", "1")); // true