How to validate a date time value in javascript to ensure that the value entered for year, month , day , hour, minute and second compose a valid Datetime object?
+3
A:
Perhaps something like that:
function ValidateDate(y, mo, d, h, mi, s)
{
var date = new Date(y, mo - 1, d, h, mi, s, 0);
var ny = date.getFullYear();
var nmo = date.getMonth() + 1;
var nd = date.getDate();
var nh = date.getHours();
var nmi = date.getMinutes();
var ns = date.getSeconds();
return ny == y && nmo == mo && nd == d && nh == h && nmi == mi && ns == s;
}
Tested with:
"OK"
ValidateDate(2001, 2, 28, 10, 35, 42)
ValidateDate(2001, 12, 29, 10, 35, 42)
ValidateDate(2000, 2, 29, 10, 35, 42)
ValidateDate(2004, 2, 29, 10, 35, 42)
ValidateDate(1970, 1, 2, 3, 4, 5)
ValidateDate(2008, 1, 15, 10, 25, 44)
"KO"
ValidateDate(2001, 2, 29, 10, 35, 42)
ValidateDate(2001, 11, 32, 10, 35, 42)
ValidateDate(2001, 15, 2, 10, 35, 42)
ValidateDate(2001, 1, 2, 25, 35, 42)
ValidateDate(2001, 5, 2, 1, 61, 42)
ValidateDate(2001, 5, 2, 1, 1, 70)
ValidateDate(2001, 0, 2, 1, 1, 1)
ValidateDate(2001, 2, 0, 1, 1, 1)
PhiLho
2009-01-15 09:32:25