You have two date fields, one is for start date and another one is for end date. You want to compare and ensure that date fields are in the correct order, like start date is before end date and other way around.
HTML Code:
<html>
<head>
</head>
<body>
<div>
Start Date :<input type=”text” name=”str_date” id=”str_date” size=”10″ value=”" onchange=”controlDate(this.id, ‘end_date’);” />
End Date :<input type=”text” name=”end_date” id=”end_date” size=”10″ value=”" onchange=”controlDate(this.id, ’str_date’);” />
</div>
</body>
</html>
You see, we add onchange javascript function to fields. And add below javascript code in the head of your page.
Javascript Code:
<script>
function controlDate(objId, dateId){
str_first_date = document.getElementById(objId).value;
str_second_date = document.getElementById(dateId).value;
first_date = conv_to_date(str_first_date);
second_date = conv_to_date(str_second_date);
if(objId == “str_date” && second_date != “”)
{
if(first_date > second_date)
{
alert(”Start date must be before end date!”);
document.getElementById(objId).value = “”;
return false;
}
}
if(objId == “end_date” && second_date != “”)
{
if(first_date < second_date)
{
alert(”End date must be after start date!”);
document.getElementById(objId).value = “”;
return false;
}
}
}
function conv_to_date(date_val)
{
var startYear = parseInt(date_val.substr(6,4), 10);
var startMonth = parseInt(date_val.substr(3,2), 10) - 1; // as per Residuum’s comment
var startDay = parseInt(date_val.substr(0,2), 10);
var dt = new Date(startYear, startMonth, startDay);
return dt;
}
</script>
