JavaScript date validation

JavaScript date validation can be done in many ways, like month range testing, then day range testing (depend on month) and so on. I suggest simpler solution. Take day, month and year from string to create a Date object. Compare day, month and year with day, month and year extracted from the Date object. If they aren't the same, than the input date is not valid.

Please try how date validation works:

Enter a date (mm/dd/yyyy):

Function seems complicated, but if you remove comments, you will see only 20 lines.

// check date JavaScript function
// if date is valid then function returns true, otherwise returns false
function isDate(txtDate){
  var objDate;  // date object initialized from the txtDate string
  var mSeconds; // milliseconds from txtDate

	// date length should be 10 characters - no more, no less
  if (txtDate.length != 10) return false;

	// extract day, month and year from the txtDate string
	// expected format is mm/dd/yyyy
	// subtraction will cast variables to integer implicitly
  var day   = txtDate.substring(3,5)  - 0;
  var month = txtDate.substring(0,2)  - 1; // because months in JS start with 0
  var year  = txtDate.substring(6,10) - 0;

	// third and sixth character should be /
	if (txtDate.substring(2,3) != '/') return false;
	if (txtDate.substring(5,6) != '/') return false;

  // test year range
  if (year < 999 || year > 3000) return false;

  // convert txtDate to the milliseconds
  mSeconds = (new Date(year, month, day)).getTime();

  // initialize Date() object from calculated milliseconds
  objDate = new Date();
  objDate.setTime(mSeconds);

  // compare input parameter date and created Date() object
  // if difference exists then date isn't valid
  if (objDate.getFullYear() != year)  return false;
  if (objDate.getMonth()    != month) return false;
  if (objDate.getDate()     != day)   return false;

	// otherwise return true
  return true;
}

And finally, see how is isDate() called in this example.

// how to use isDate() JavaScript function
// this function is called on button click event
function checkDate(){
	// define date string to test
	var txtDate = document.getElementById('txtDate').value;
	// check date and print message
	if (isDate(txtDate)) alert('OK');
	else alert('Invalid date format!');
}

Related posts

Bookmark and Share

6 Responses to “JavaScript date validation”

  1. red_screen says:

    Nice Script!

  2. newbie says:

    Thanks, one of the most elegant scripts I've seen that checks the date ...

  3. Amal says:

    Nice work!! Cleverly done.

  4. everest says:

    good script

  5. b0ris says:

    A very good one, thanks, you spared me some work hours :)

  6. rivka says:

    thank's a lot!a great great solution

Leave a Reply