Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Date Validation in JavaScript

2.64/5 (11 votes)
21 Apr 2006CPOL 1  
An article to validate dates in JavaScript.

Introduction

This code is developed to validate date entered in a web page. I found several other code snippets that provide a solution, but they are all vague and confusing, while this JavaScript script provides an easy method of validating a date. Check out this.

Using the code

Shown below is the core code for the date validation, written in JavaScript:

JavaScript
//
 function IsValidDate(Day,Mn,Yr){
    var DateVal = Mn + "/" + Day + "/" + Yr;
    var dt = new Date(DateVal);

    if(dt.getDate()!=Day){
        alert('Invalid Date');
        return(false);
        }
    else if(dt.getMonth()!=Mn-1){
    //this is for the purpose JavaScript starts the month from 0
        alert('Invalid Date');
        return(false);
        }
    else if(dt.getFullYear()!=Yr){
        alert('Invalid Date');
        return(false);
        }
        
    return(true);
 }
//

If you plan to add this to a custom validator in ASP.NET, then the following method will do:

The code below is written for calling the above JavaScript function:

JavaScript
function CallDateFun(sender, args){
   var d=document.getElementById("DayDropDownListCtl").value
   var m=document.getElementById("MonthDropDownListCtl").value
   var y=document.getElementById("YearDropDownListCtl").value

   if(IsValidDate(d,m,y))
        args.IsValid=true;
   else
        args.IsValid=false;
}

This is the code for the custom validator:

HTML
<asp:CustomValidator ID="CustomDateValidatorCtl" 
  runat="server"  ClientValidationFunction="CallDateFun" 
  Text="Invalid Date" ControlToValidate="DayDropDownListCtl">
</asp:CustomValidator>

Note: DayDropDownListCtl, MonthDropDownListCtl, and YearDropDownListCtl are the dropdown lists for the date, month, and year, respectively.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)