Tuesday, 22 October 2013

Custom validation with ASP.NET validator for max date and min date

Hello Friends,
you want to validate any text box as a minimum and maximum date, then use below code.

Step 1: A Custom Validator add in .aspx page

<asp:TextBox ID="txtDOJ" runat="server" PlaceHolder="Date of Journey"></asp:TextBox>
<asp:CustomValidator runat="server" ID="valDateRange" ControlToValidate="txtDOJ"
OnServerValidate="valDateRange_ServerValidate" ErrorMessage="enter valid date" />

Step 2: Code-behind .cs page

protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
        {
            DateTime minDate = DateTime.Parse(DateTime.Now.ToLongDateString());
            DateTime maxDate = DateTime.Parse(DateTime.Now.AddMonths(2).ToLongDateString());
            DateTime dt;

            args.IsValid = (DateTime.TryParse(args.Value, out dt)
                            && dt <= maxDate
                            && dt >= minDate);
        }


that's it...

No comments:

Post a Comment

Search on This Blog