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">
</asp:CustomValidator>

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
    
    fromDate.setUTCDate(fdd);
    fromDate.setUTCMonth(fmm-1);
    fromDate.setUTCFullYear(fyyyy);
    
    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
    
    toDate.setUTCDate(tdd);
    toDate.setUTCMonth(tmm-1);
    toDate.setUTCFullYear(tyyyy);
    //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;
    else
        args.IsValid = true;
}
</script>

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.

 

Thanks

~Brij

3 Comments

Comments have been disabled for this content.