Tuesday, 20 March 2012

Custom validation to calculate difference between date of birth DOB for any format using asp.net c#


How to use Custom validation to calculate difference between two date of birth DOB of any format using asp.net c# ?

We could customize our DOB format of any formate.

The following code base checks / validates year difference between two dates.

Same aspx code demo:

<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtDOB" onservervalidate="cusCustom_ServerValidate" errormessage="Invalid D.O.B(Below 18 Yrs)" ValidationGroup="v" SetFocusOnError="true" Display="Dynamic" />

C# Code behind 


private int CalculateDifference(DateTime Date1, DateTime Date2)
        {
            TimeSpan span = Date2.Subtract(Date1);
            int years = (int)(span.Days / 365.25);
            return years;
        }

        protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            int i;
            DateTime FromDate = DateTime.ParseExact(e.Value.ToString(), "dd/MM/yyyy", null);
            DateTime ToDate = DateTime.ParseExact(DateTime.Now.ToString("dd/MM/yyyy"), "dd/MM/yyyy", null);
            i = CalculateDifference(FromDate, ToDate);
            if (i >= 18)
                e.IsValid = true;
            else
                e.IsValid = false;
        }

No comments:

Post a Comment