Custom Validation for Date of Birth using three dropdownlist


By zafar iqbal
Printer Friendly Version
View My Articles

  

This article is used to validate the date of birth having 3 dropdownlist control.first dropdownlist control populates data for Days second for Months and third for Years.this article is exactly usefull for the users those want to validate DOB containing three dropdownlist.Datasources for Days and Months populates from two XML Files(DD.xml and MM.xml) in this project.



Creatinng two xml files for Days and Months where thease will be used as a datasource to bind the dropdownlist controls for days and months only

<?xml version="1.0" encoding="UTF-8" ?>

- <DD>
  <DD value="DD" name="DD" />
  <DD value="1" name="01" />
  <DD value="2" name="02" />
  <DD value="3" name="03" />
  <DD value="4" name="04" />
  <DD value="5" name="05" />
  <DD value="6" name="06" />
  <DD value="7" name="07" />
  <DD value="8" name="08" />
  <DD value="9" name="09" />
  <DD value="10" name="10" />
  <DD value="11" name="11" />
  <DD value="12" name="12" />
  <DD value="13" name="13" />
  <DD value="14" name="14" />
  <DD value="15" name="15" />
  <DD value="16" name="16" />
  <DD value="17" name="17" />
  <DD value="18" name="18" />
  <DD value="19" name="19" />
  <DD value="20" name="20" />
  <DD value="21" name="21" />
  <DD value="22" name="22" />
  <DD value="23" name="23" />
  <DD value="24" name="24" />
  <DD value="25" name="25" />
  <DD value="26" name="26" />
  <DD value="27" name="27" />
  <DD value="28" name="28" />
  <DD value="29" name="29" />
  <DD value="30" name="30" />
  <DD value="31" name="31" />
  </DD>
..save it as a DD.xml....
second xml file is following....
<?xml version="1.0" encoding="UTF-8" ?>
- <MM>
  <MM value="MM" name="MM" />
  <MM value="1" name="Jan" />
  <MM value="2" name="Feb" />
  <MM value="3" name="Mar" />
  <MM value="4" name="Apr" />
  <MM value="5" name="May" />
  <MM value="6" name="Jun" />
  <MM value="7" name="Jul" />
  <MM value="8" name="Aug" />
  <MM value="9" name="Sep" />
  <MM value="10" name="Oct" />
  <MM value="11" name="Nov" />
  <MM value="12" name="Dec" />
  </MM>
save it as a MM.xml........
now take three dropdownlist controls on the page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html>
<head runat="server">
    <title>Custom validation for Date of Birth</title>
    <script language="javascript" type="text/javascript">
  function SetBirthDate()
        {
            var ddlMonthID = "<%=ddlMonth.ClientID %>", ddlDayID = "<%=ddlDay.ClientID %>", ddlYearID = "<%=ddlYear.ClientID %>", txtBirthDateID = "<%=txtBirthDate.ClientID %>";
            var element = document.getElementById(txtBirthDateID);
            if (element==null) return;
                 element.value = "";
           var myMonthStr = parseInt(document.getElementById(ddlMonthID).value);
           var myDayStr =   parseInt(document.getElementById(ddlDayID).value);
           var  myYearStr = parseInt(document.getElementById(ddlYearID).value);           
          
            if(isNaN(myMonthStr)==false && isNaN(myDayStr)==false && isNaN(myYearStr)==false)
               element.value = myMonthStr  + "-" + myDayStr + "-" +myYearStr;
          }
     function CheckDate(oSrc,args)
         {
         //The below two ids are view source of the aspx file
         //of the respective controls one is Entered date and the other is hidden field date
         var dateOfBirthClientID =  document.getElementById('txtBirthDate');
         var systemDateClientID =  document.getElementById('hdnCurrentDate'); 
         var dateOfBirth = dateOfBirthClientID.value;
       
         var systemDate = systemDateClientID.value;
         var ArrDob =   dateOfBirth.split("-");
         var DobMonth = ArrDob[0];
         var DobDate   = ArrDob[1];
         var DobYear   = ArrDob[2];
         var ArrSysDate =   systemDate.split("-");
         var sysDD = ArrSysDate[0];
         var sysMM = ArrSysDate[1];
         var sysYYYY = ArrSysDate[2];
         var SysDate = parseInt(sysDD);
         var SysMonth = parseInt(sysMM);
         var SysYear = parseInt(sysYYYY);
       
         var returndays = isleap(DobYear);
        
         if(DobDate > returndays && DobMonth=="2")
         {
         args.IsValid = false;
         return;
         }
        if(DobMonth % 2==0 && DobDate=="31")
        {
         args.IsValid = false;
         return;
        }
         if(DobYear > SysYear)
         {
         args.IsValid = false;
         return;
         } 
         else if((DobYear == SysYear) && (DobMonth > SysMonth))
         {
         args.IsValid = false;
         return;
         }
         else if((DobYear == SysYear) && (DobMonth == SysMonth) && (DobDate > SysDate))
         {
          args.IsValid = false; 
          return;
          }
          args.IsValid = true;
    }
        /////////////////////////////////////////////////////////////////////////////////////
        //.... function to check the leap year....
        // February has 29 days in any year evenly divisible by four,
        // Except for centurial years which are not also divisible by 400.
        function isleap(yr)
        {
         if ((parseInt(yr)%4) == 0)
         {
          if (parseInt(yr)%100 == 0)
          {
            if (parseInt(yr)%400 != 0)
            {
              return 28;
            }
            if (parseInt(yr)%400 == 0)
            {
              return 29;
            }
          }
          if (parseInt(yr)%100 != 0)
          {
            return 29;
          }
         }
         if ((parseInt(yr)%4) != 0)
         {
           return 28;
         }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table border="0" cellpadding="0" cellspacing="0" width="837px">
                <tr>
                    <td width="10%">
                    </td>
                    <td width="5%">
                    </td>
                    <td width="75%">
                    </td>
                    <td width="5%">
                    </td>
                    <td width="5%">
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                    </td>
                    <td colspan="2">
                    </td>
                    <td colspan="1">
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                        DOB:</td>
                    <td colspan="2">
                        <asp:DropDownList ID="ddlDay" runat="server">
                        </asp:DropDownList>
                        <asp:DropDownList ID="ddlMonth" runat="server">
                        </asp:DropDownList>
                        <asp:DropDownList ID="ddlYear" runat="server">
                            <asp:ListItem Value="YYYY">YYYY</asp:ListItem>
                        </asp:DropDownList>
                        <asp:CustomValidator ID="custDateOfBirth" runat="server" ValidationGroup="vgValidation"
                            Display="Dynamic" ControlToValidate="txtBirthDate" ClientValidationFunction="CheckDate"
                            ErrorMessage="Invalid Date of Birth">
                        </asp:CustomValidator>
                        <asp:RequiredFieldValidator ID="rfvDay" runat="server" ControlToValidate="ddlDay"
                            Display="Dynamic" ErrorMessage="Day  Required" InitialValue="DD" SetFocusOnError="True"
                            ValidationGroup="vgValidation"></asp:RequiredFieldValidator>
                        &nbsp;<asp:RequiredFieldValidator ID="rfvMonth" runat="server" ControlToValidate="ddlMonth"
                            Display="Dynamic" ErrorMessage="Month Required" InitialValue="MM" SetFocusOnError="True"
                            ValidationGroup="vgValidation"></asp:RequiredFieldValidator>&nbsp;<asp:RequiredFieldValidator
                                ID="rfvYear" runat="server" ControlToValidate="ddlYear" Display="Dynamic" ErrorMessage="Year Required"
                                InitialValue="YYYY" SetFocusOnError="True" ValidationGroup="vgValidation"></asp:RequiredFieldValidator>
                        <div id="divdateofbirth" style="display: none;">
                            <asp:TextBox ID="txtBirthDate" runat="server" Width="10px"></asp:TextBox>
                        </div>
                    </td>
                    <td colspan="1">
                    </td>
                </tr>
                <tr height="10px">
                    <td>
                    </td>
                    <td>
                    </td>
                    <td align="center">
                    </td>
                    <td>
                        <asp:HiddenField ID="hdnCurrentDate" runat="server" />
                    </td>
                    <td>
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                    </td>
                    <td align="left">
                        <asp:Button ID="btnValidate" OnClientClick="SetBirthDate();" runat="server" Text="Validate"
                            ValidationGroup="vgValidation" /></td>
                    <td>
                    </td>
                    <td>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
...............................
Make a folder named "BusinessLogic" within App_Code Folder...
... now create a class file name it as a "DataBL.cs"
...next come to write code within this class file.....
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for DataBL
/// </summary>
public class DataBL
{
    public DataBL()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public static void Bind(ref DropDownList ddl, string type)
    {
        DataSet ds = new DataSet();
        if (type == "Day")
            ds.ReadXml(HttpContext.Current.Server.MapPath("./DD.xml"));
        else
            ds.ReadXml(HttpContext.Current.Server.MapPath("./MM.xml"));
        ddl.DataSource = ds;
        ddl.DataTextField = "name";
        ddl.DataValueField = "value";
        ddl.DataBind();
    }
    public static void BindYr(ref DropDownList ddl)
    {
        for (int i = 1950; i <= DateTime.Now.Year; i++)
        {
            ddl.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
    }
}
------------------------------------------------------------------------
..now write following code into the code behind file.........
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            hdnCurrentDate.Value = DateTime.Now.ToString("dd-MM-yyyy");
            DataBL.Bind(ref ddlDay,"Day");
            DataBL.Bind(ref ddlMonth,"Month");
            DataBL.BindYr(ref ddlYear);
        }
    }
}




button
 
Article Discussion: Custom Validation for Date of Birth using three dropdownlist
zafar iqbal posted at 09-Jul-08 02:20
Original Article

 
bug fix for last day of July, August, Sep...., December
christian theriault replied to zafar iqbal at 07-Oct-08 04:13

following javascript snippet is incorrect: 

         if(DobMonth % 2==0 && DobDate=="31")
        {
         args.IsValid = false;
         return;
        }

For instance December does have 31 days althought 12 % 2 is 0...

to fix it:

#1) I replaced the function "isleap( )" with the following one which does a bit more work:

function MonthsLastDay(year,month){
    if (month==2)
         return ((year % 4 == 0) && ( (year % 100 != 0) || (year % 400 == 0))) ? 29 : 28;
    return (month==4 || month==6 || month==9 || month==11) ? 30 : 31;
}

#2) I replaced the part which was doing the day-of-the-month check with: 

if (date_DOB_Day > MonthsLastDay(date_DOB_Year, date_DOB_Month)) {
    arguments.IsValid=false;
    return;
}


promotion
Silverlight    WPF    WCF    WWF    LINQ   
JavaScript    AJAX    ASP.NET    XAML   
C#    VB.NET    VB 6.0    GDI+    IIS    XML   
.NET Generics    Anonymous Methods    Delegate   
Visual Studio .NET    Expression Blend    Virus   
Windows Vista    Windows XP    Windows Update   
Windows 2003 Server    Windows 2008 Server   
SQL Server    Microsoft Excel    Microsoft Word   
SharePoint    BizTalk    Virtual Earth   
.NET Compact Framework    Web Service   

"Everything" RSS / ATOM Feed Parser
How to send and receive messages through message queuing in .Net
How to Read text file as database
SQL Server 2005 Paging Performance Tip
Display code of web page.
Fully Scalable Excel File Importer class for .net using Microsoft Jet driver
Generic Chart Color Manager class that can be used for any charts
Helper class to style the infragistics wingrid
Using Reflection to detemine as Assembly Info in and out.
Helper class to play with Window (Owners and position)
Resolving displayname from the culture using the XmlLanguage and LanguageSpecificStringDictionary class
Manipulate file attributes in VB.NET
Forms Based Authentication Filtered Content Editor for SharePoint
How to create a Tree View of the Windows Folder and extract all the file-folder info.
How to use AssemblyInfo.cs file in win forms to provide much needed information on Assemblies
Sorting In Datagrid
Helper class to work with NativeMethods in the native api's
Silverlight Line Of Business Applications With Offline WPF Versions
C# : Database monitoring system using XML file
C# : Adding ComboBox to ListView SubItem
Sum of Numbers Captcha: Keeping it Simple
C# Create a Piechart for the specified Hard Disk Drive Utilization
Extension Methods for DataSet and DataTable that makes tasks easier
Accessing IIS Hosted WCF Services from PHP
Helper class that provides most commonly used Extension Methods for DateTime object
Helper class to work with a Status Bar in WPF.
Finding Unmatched Records in Dataset Tables Using Linq
Silverlight Toolkit: Autocomplete TextBox Stock Symbols and Chart
COOL Auto Complete textbox using javascript
Creating a Serializable Log Entry for Microsoft Enterprise Library to log to a Database
ASP.NET Searching Values in Datagrid