Validate Date With JQuery And Date Object
Posted by in Javascript March 14, 2012 Leave a comment

This article gives a piece of JavaScript code to validate entered date (birthday for example) which is entered by a user. When the user enters an invalid date, such as abcdef, 99/99/9999 or 02/29/2011, a JavaScript popup appears with the validation message.

JQuery Validate Date With Date Object

Example below will use JQuery (which is downloaded from Google CDN) and Date object to validate.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JQuery Validate Date</title>
<meta name="robots" content="noindex, nofollow" />
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
</head>
 
<body>
<script language="javascript">
function validate()
{
	var strDate = jQuery("#txtDate").val();
	strDate = jQuery.trim(strDate);
 
	var arrDate = strDate.split('/');
 
	var day = parseInt(jQuery.trim(arrDate[1]), 10);
	var month = parseInt(jQuery.trim(arrDate[0]), 10);
	var year = parseInt(jQuery.trim(arrDate[2]), 10);
 
 
	var date = new Date(year, month-1, day);
	var convertedDate = "" + date.getFullYear() + (date.getMonth()+1) + date.getDate();
	var givenDate = "" + year + month + day;
 
	if(givenDate == convertedDate)
	{
		alert("The given date is VALID!");
		return true;
	}
	else
	{
		alert("The given date IS NOT VALID!");
		return false;
	}
}
</script>
<table>
	<tr>
		<td align="left">Enter a Date in the text box then click Validate button:</td>
	</tr>
	<tr>
		<td><input type="text" id="txtDate" name="txtDate" style="width:200px;" value="02/29/2011" /> (mm/dd/yyyy)</td>
	</tr>
	<tr>
		<td><input type="button" id="btnValidate" value="Validate" onclick="return validate();" /></td>
	</tr>
</table>
 
</body>
</html>
Validate Date With JQuery And Date Object

Validate Date With JQuery And Date Object

+ Download Source Code Validate Date With JQuery And Date Object
+ View our demonstration page to see How it works

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com