Click here to Skip to main content
Licence 
First Posted 27 Jan 2003
Views 160,615
Bookmarked 46 times

Date Validator Custom Web Control

By | 26 Mar 2003 | Article
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:

<%@ 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

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralSystem.Web.UI.Page.RegisterClientScriptBlock is Obsolete !!!!!!!!!!! Pinmemberoscarlagatta8:07 13 Sep '09  
QuestionHow can i place a datepicker control in asp.net form Pinmembereajazch222:34 22 Sep '07  
GeneralControlToValidate disappears PinmemberTasha Basha9:55 30 Jan '06  
GeneralBig mistake... PinmemberCarl Mercier8:31 26 Mar '04  
GeneralRe: Big mistake... PinmemberCarl Mercier8:42 26 Mar '04  
GeneralParser Error Message PinmemberVannela0:54 3 Feb '04  
GeneralRe: Parser Error Message Pinmemberharisahmed5:15 26 Apr '06  
GeneralThe ClientScript Pinmemberilikc0de9:23 3 Dec '03  
GeneralNicer way of doing JavaScript in code behind PinsussPaul Tallett.20:46 31 Mar '03  
GeneralRe: Nicer way of doing JavaScript in code behind PinsussAnonymous15:34 9 Dec '03  
GeneralRe: Nicer way of doing JavaScript in code behind PinsussAnonymous7:58 3 Feb '05  
GeneralData type validators aren't missing PinmemberEric Woodruff12:35 30 Mar '03  
GeneralRe: Data type validators aren't missing PinmemberManowar22:31 30 Mar '03  
GeneralRe: Data type validators aren't missing PinPopularmemberEric Woodruff10:03 31 Mar '03  
GeneralRe: Data type validators aren't missing PinmemberManowar19:39 31 Mar '03  
GeneralRe: Data type validators aren't missing PinsussAnonymous9:01 3 Feb '05  

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

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

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