JavaScript
Article

jQuery Check if Date is Valid

By Sam Deering

Simple JavaScript Function to to check if date is valid.

function isValidDate(s) {
  var bits = s.split('/');
  var d = new Date(bits[2] + '/' + bits[1] + '/' + bits[0]);
  return !!(d && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[0]));
}

//Test it!
var currentDate = new Date('31/09/2011');
console.log(isValidDate(currentDate.toString()));
console.log(isValidDate('30/09/2011'));

JavaScript Function to to get the number of days in a month.

function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}

//Test it!
daysInMonth('09','2011');
//Output: 30

Also See:

JavaScript Function to to check if date is valid if not set it to last day in month.

/* check a date is valid, if not revert to last day in month */
validateDateLastDayMonth: function()
{
	/* helpers */
	function isValidDate(s) {
	  var bits = s.split('/');
	  var d = new Date(bits[2] + '/' + bits[1] + '/' + bits[0]);
	  return !!(d && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[0]));
	} 

	function daysInMonth(month, year) {
		return new Date(year, month, 0).getDate();
	}
	
	/* init */
	var currentDate = new Date(),
	currentMonth = currentDate.getMonth() + 1,
	lastDayOfMonth = new Date(currentDate.getFullYear(), (currentDate.getMonth() - 1), 0).getDate(),
	departureDate = FCL.DATETIME.futureDateDays(14),
	depDate = departureDate.split('/'),
	departureDateMonth = depDate[1];
	if (departureDateMonth != currentMonth) {
		departureDate = FCL.DATETIME.leadingZero(lastDayOfMonth) +'/'+ FCL.DATETIME.leadingZero(currentMonth) +'/'+ depDate[2];
	}
	
	/* validate date */
	if (!isValidDate(departureDate.toString()))
	{
		var bits = departureDate.split('/');
		departureDate = FCL.DATETIME.leadingZero(daysInMonth(bits[1],bits[2])) +'/'+ FCL.DATETIME.leadingZero(currentMonth) +'/'+ depDate[2];
	}
	
	$('input[name="depDate"]').val(departureDate);
}

No Reader comments

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.