JavaScript Validation: Date Range

This quick post shows how to validate two date fields by comparing their values. When there is two date fields in a page like From Date & To Date , then generally arises a requirement to show a message that From Date can not be greater than To Date or, something like that. This is required when the user inputs a greater date in  the From Date field than To Date.


Here I have taken two TextBox for inputting dates named- txtFromDate & txtToDate

var FromDt = document.getElementById("<%=txtFromDate.ClientID %>").value;
var ToDt = document.getElementById("<%=txtToDate.ClientID %>").value;

if (Date.parse(FromDt.trim()) > Date.parse(ToDt.trim())) {
    alert("Please check date range!\nFrom Date cannot be greater than To Date!")
    return false;