Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Validate if Date exists 1

Status
Not open for further replies.

MasterKaos

Programmer
Jan 17, 2004
107
0
0
GB
Does Javascript have a built-in funciton that will check if a given date exists? For example return true for Feb 29th 2004 but false for Feb 29th 2003. I know PHP and MySQL have such funcitons, but i'd like to do all the validation client-side.

----------------------------------------------------------------------------
The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.
 

This should do the job for you. Set the 3 variables at the top, and run:

Code:
var yearToCheck = 2004;
var monthToCheck = 1;	// 0-based... so 1 = february
var dateToCheck = 30;
var dateObj = new Date(yearToCheck, monthToCheck, dateToCheck);
if (dateObj.getFullYear() == yearToCheck && dateObj.getMonth() == monthToCheck && dateObj.getDate() == dateToCheck) {
	alert('Valid date');
} else {
	alert('Invalid date');
}

It works by creating a new date object, and setting it to the date you want to check. For valid dates, reading back the component parts of the date would reveal the same values you had initially set. For invalid dates, the date object re-jigs the values turning them into a valid date.

So all we do is test the values to make sure they were the same as the ones plugged into the date object to begin with.

Hope this helps,
Dan
 
Thanx BillyRay!

I was so close, like i figured if the month is greater than the original month it means it is not valid, it's the 0 based bit that messed me up!

/me has been sitting in PHP too long, has forgotten the joys of 0 based java(script) :)

----------------------------------------------------------------------------
The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.
 

Does anyone know why only the month is 0-based, while the year and date are not? I can't figure it out ;o)

Dan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top