Click here to Skip to main content
Click here to Skip to main content

Date Validator Custom Web Control

By , 26 Mar 2003
 

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:

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

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

<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:

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:

<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

About the Author

ManOwaR
Web Developer
Italy Italy
Member
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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralSystem.Web.UI.Page.RegisterClientScriptBlock is Obsolete !!!!!!!!!!!memberoscarlagatta13 Sep '09 - 8:07 
QuestionHow can i place a datepicker control in asp.net formmembereajazch222 Sep '07 - 22:34 
GeneralControlToValidate disappearsmemberTasha Basha30 Jan '06 - 9:55 
GeneralBig mistake...memberCarl Mercier26 Mar '04 - 8:31 
GeneralRe: Big mistake...memberCarl Mercier26 Mar '04 - 8:42 
GeneralParser Error MessagememberVannela3 Feb '04 - 0:54 
GeneralRe: Parser Error Messagememberharisahmed26 Apr '06 - 5:15 
GeneralThe ClientScriptmemberilikc0de3 Dec '03 - 9:23 
GeneralNicer way of doing JavaScript in code behindsussPaul Tallett.31 Mar '03 - 20:46 
GeneralRe: Nicer way of doing JavaScript in code behindsussAnonymous9 Dec '03 - 15:34 
GeneralRe: Nicer way of doing JavaScript in code behindsussAnonymous3 Feb '05 - 7:58 
GeneralData type validators aren't missingmemberEric Woodruff30 Mar '03 - 12:35 
GeneralRe: Data type validators aren't missingmemberManowar30 Mar '03 - 22:31 
GeneralRe: Data type validators aren't missingmemberEric Woodruff31 Mar '03 - 10:03 
GeneralRe: Data type validators aren't missingmemberManowar31 Mar '03 - 19:39 
GeneralRe: Data type validators aren't missingsussAnonymous3 Feb '05 - 9:01 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 27 Mar 2003
Article Copyright 2003 by ManOwaR
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid