Click here to Skip to main content
15,886,689 members
Articles / Web Development / ASP.NET
Article

Date Validator Custom Web Control

Rate me:
Please Sign up or sign in to vote.
3.38/5 (16 votes)
26 Mar 20032 min read 181.5K   1.6K   46   16
A custom web control to validate a user hand-inserted date.

Introduction

The validators shipped with .NET are great tools to check and validate what the user enters on a web form, before processing it. Unfortunately some every-day-useful validators are missing...Though some help can come from the web (where you can find CheckBox and CheckBoxList validators), a control that perfectly validates a date inserted by hand by the user (so without combo-boxes) is still missing. With the DateValidator control this gap has been filled. User can insert date in a common text box and that's all: you won't have to bother about validating their input, the only request is that the date must be in the format dd/mm/yyyy. After you download the source code you have to create a project and then add the source file to the project. Now you can compile so that you'll obtain a DLL. Now you can include the web control in your project (and you can also add it the to ToolBox) and then you just have to register the control as usual:

ASP.NET
<%@ Register TagPrefix="dgw" 
  Namespace="Doing.General.WebControls.Validators" 
  Assembly="Doing.WebControls" %>

Then choose the control to bind as you do for a usual validator.

HTML
<asp:textbox id="txtBirth" runat="server" cssclass="TEXT1"/>
<dgw:datevalidator 
    id="dvBirth" 
    runat="server" 
    display="Dynamic" 
    controltovalidate="txtBirth" 
    errormessage="Date not valid"/>

This control, in fact, inherits from BaseValidator, so you have all the methods and the properties you're used to. From a technical point of you, probably the most interesting is the ClientScript function, where the necessary JavaScript code to perform client-side navigation is built:

C#
protected void ClientScript() {
    this.Attributes["evaluationfunction"] = "doingValidateDate";

    StringBuilder validatorScript = new StringBuilder();
    validatorScript.Append("<script language=\"javascript\">");
    validatorScript.Append("\r");
    validatorScript.Append("function doingValidateDate(val) {");
    validatorScript.Append("\r");
    validatorScript.Append("var oDate = 
            document.all[val.controltovalidate];");
    validatorScript.Append("\r");
    validatorScript.Append("var sDate = oDate.value;");
    validatorScript.Append("if (sDate == \"\") return true;");
    validatorScript.Append("\r");
    validatorScript.Append("var iDay, iMonth, iYear;");
    validatorScript.Append("\r");
    validatorScript.Append("var arrValues;");
    validatorScript.Append("\r");
    validatorScript.Append("var today = new Date();");
    validatorScript.Append("\r");
    validatorScript.Append("arrValues = sDate.split(\"/\");");
    validatorScript.Append("\r");
    validatorScript.Append("iDay = arrValues[0];");
    validatorScript.Append("\r");
    validatorScript.Append("iMonth = arrValues[1];");
    validatorScript.Append("\r");
    validatorScript.Append("iYear = arrValues[2];");
    validatorScript.Append("\r");
    validatorScript.Append
      ("if ((iMonth == null) || 
      (iYear == null)) return false;");
    validatorScript.Append("\r");
    validatorScript.Append
      ("if ((iDay > 31) || (iMonth > 12) 
      || (iYear < 1900 || 
      iYear > today.getFullYear())) return false;");
    validatorScript.Append("\r");
    validatorScript.Append
      ("var dummyDate = new Date(iYear, iMonth - 1, iDay);");
    validatorScript.Append("\r");
    validatorScript.Append
      ("if ((dummyDate.getDate() != iDay) || 
      (dummyDate.getMonth() != iMonth - 1) || 
      (dummyDate.getFullYear() != iYear)) return false;");
    validatorScript.Append("\r");
    validatorScript.Append("return true;");
    validatorScript.Append("\r");
    validatorScript.Append("}");
    validatorScript.Append("\r");
    validatorScript.Append("</script>");
    this.Page.RegisterClientScriptBlock
      ("doingValidateDate", validatorScript.ToString());
}

This one, once compiled and processed produces this JavaScript code:

JavaScript
<script language="javascript">
function doingValidateDate(val) {
    var oDate = document.all[val.controltovalidate];
    var sDate = oDate.value;
    if (sDate == "") return true;
    var iDay, iMonth, iYear;
    var arrValues;
    var today = new Date();
    arrValues = sDate.split("/");
    iDay = arrValues[0];
    iMonth = arrValues[1];
    iYear = arrValues[2];
    if ((iMonth == null) || (iYear == null)) return false;
    if ((iDay > 31) || (iMonth > 12) || 
        (iYear < 1900 || iYear > today.getFullYear())) 
      return false;
    var dummyDate = new Date(iYear, iMonth - 1, iDay);
    if ((dummyDate.getDate() != iDay) || 
      (dummyDate.getMonth() != iMonth - 1) || 
      (dummyDate.getFullYear() != iYear)) 
         return false;
    return true;
}
</script>

Improvements

Of course this validator can be improved a lot. Probably the most useful features will be the ability the check date against a valid range, and the possibility to support more date formats (e.g.: mm/dd/yyyy or yyyy/mm/dd)

Greetings

I must thanks Donny Mack for having written a wonderful tutorial [^] that helped me to understand and build this web user control.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Italy Italy
Born in 1977, works as a freelancer, focusing on Database / Software Architecture.
In the free time writes articles for two of the major Italian programming magazines (Computer Programming and VBJ) and also develops nice and useful programs.
His major interests and skills are the .NET framework (C# in particular) and SQL Server.

Comments and Discussions

 
GeneralSystem.Web.UI.Page.RegisterClientScriptBlock is Obsolete !!!!!!!!!!! Pin
oscarlagatta13-Sep-09 8:07
oscarlagatta13-Sep-09 8:07 
QuestionHow can i place a datepicker control in asp.net form Pin
eajazch222-Sep-07 22:34
eajazch222-Sep-07 22:34 
GeneralControlToValidate disappears Pin
Tasha Basha30-Jan-06 9:55
Tasha Basha30-Jan-06 9:55 
GeneralBig mistake... Pin
Carl Mercier26-Mar-04 8:31
Carl Mercier26-Mar-04 8:31 
GeneralRe: Big mistake... Pin
Carl Mercier26-Mar-04 8:42
Carl Mercier26-Mar-04 8:42 
GeneralParser Error Message Pin
Vannela3-Feb-04 0:54
Vannela3-Feb-04 0:54 
GeneralRe: Parser Error Message Pin
harisahmed26-Apr-06 5:15
harisahmed26-Apr-06 5:15 
GeneralThe ClientScript Pin
ilikc0de3-Dec-03 9:23
ilikc0de3-Dec-03 9:23 
GeneralNicer way of doing JavaScript in code behind Pin
Paul Tallett.31-Mar-03 20:46
sussPaul Tallett.31-Mar-03 20:46 
GeneralRe: Nicer way of doing JavaScript in code behind Pin
Anonymous9-Dec-03 15:34
Anonymous9-Dec-03 15:34 
GeneralRe: Nicer way of doing JavaScript in code behind Pin
Anonymous3-Feb-05 7:58
Anonymous3-Feb-05 7:58 
GeneralData type validators aren't missing Pin
Eric Woodruff30-Mar-03 12:35
professionalEric Woodruff30-Mar-03 12:35 
GeneralRe: Data type validators aren't missing Pin
manowar30-Mar-03 22:31
manowar30-Mar-03 22:31 
GeneralRe: Data type validators aren't missing Pin
Eric Woodruff31-Mar-03 10:03
professionalEric Woodruff31-Mar-03 10:03 
GeneralRe: Data type validators aren't missing Pin
manowar31-Mar-03 19:39
manowar31-Mar-03 19:39 
GeneralRe: Data type validators aren't missing Pin
Anonymous3-Feb-05 9:01
Anonymous3-Feb-05 9:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.