Javascript Date Comparision using CustomValidator And String to Date Conversion using JavaScript

This function calculates the difference between the two Date, and Validate it,

I used this function to validate the difference between the From Date and To Datefor not more then 366 days(to cover the leap year also) or less then 0,

This function is called through the CustomValidator of ASP.NET, but you can also use this without the CustomValidator.


To execute the Custom JavaScript from your Validation Control you have to add CustomValidator, the code of which is given belo

<asp:CustomValidator runat="server" ID="custDateValidator"
ClientValidationFunction="CompareDates" Display="Dynamic"
ErrorMessage="The number of date to be included in report must be between 1 and 366">

This following piece of code also shows you how to convert the String to DateTime,because in my Form I am taking the Dates from two HTML TextBoxes, which by default is String, so I had to write seperate piece of code which will convert String to DateTime.

<script language="JavaScript" type="text/javascript">
function CompareDates(source, args) 
    var fromDate = new Date();
    var txtFromDate = document.getElementById("txtDateFrom").value;
    var aFromDate = txtFromDate.split("/");
    /*Start 'Date to String' conversion block, this block is required because javascript do not provide any direct function to convert 'String to Date' */
    var fdd = aFromDate[0]; //get the day part
    var fmm = aFromDate[1]; //get the month part
    var fyyyy = aFromDate[2]; //get the year part
    var toDate = new Date();
    var txtToDate = document.getElementById("txtDateTo").value;
    var aToDate = txtToDate.split("/");
    var tdd = aToDate[0]; //get the day part
    var tmm = aToDate[1]; //get the month part
    var tyyyy = aToDate[2]; //get the year part
    //end of 'String to Date' conversion block
    var difference = toDate.getTime() - fromDate.getTime();
    var daysDifference = Math.floor(difference/1000/60/60/24);
    difference -= daysDifference*1000*60*60*24;
    //if diffrence is greater then 366 then invalidate, else form is valid
    if(daysDifference > 366 daysDifference < 0)
        args.IsValid = false;
        args.IsValid = true;

I know there can be lots of better way to do this, please post as comments if you have some good ideas and example to do the same.





Comments have been disabled for this content.