Monday, July 19, 2004

JavaScript Function Validate Date (valid date)

This function returns True if the passed text is a valid date, False if it is not.


/*
ValidDate - true for valid date, false for invalid
*/
function IsValidDate(PossibleDate)
{
var PDate = new String(PossibleDate);

var regex = /(^\d{1,2})\/(\d{1,2})\/(\d{4,4})|(^\d{1,2})\/(\d{1,2})\/(\d{2,2})/;

if( regex.test(PDate) )
{
var month = new String(RegExp.$1);
var day = new String(RegExp.$2);
var year = new String(RegExp.$3);
if( month.length == 0 )
{
month = new String(RegExp.$4);
day = new String(RegExp.$5);
year = new String(RegExp.$6);
}

var today = new Date();
var thisYear = new String(today.getFullYear());

if( year.length == 2 )
{
if( year > 50 )
{
year = String(Number(thisYear.substring(0,2))-1) + year;
}
else
{
year = thisYear.substring(0,2) + year;
}
}

if( month < 1 || month > 12 ) { return false; }

if( day < 1 || day > 31 ) { return false; }

if ((month==4 || month==6 || month==9 || month==11) && day>30) { return false; }

if (month == 2) // check for february 29th
{
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap))
{
return false;
}
}

if( (Number(year) < Number(thisYear) - 250) ||
(Number(year) > Number(thisYear) + 250) )
{ return false; }

return true;
}
return false;
}