Hithesh
Hithesh

Reputation: 449

Custom Validator validation not firing for textbox in asp.net

<asp:TextBox ID="txtDOB" runat="server" CssClass="textbox_width_height" 
placeholder="DD/MM/YYYY" CausesValidation="true"></asp:TextBox>

<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" 
      Enabled="true" ValidateEmptyText="true" SetFocusOnError="true"
      OnServerValidate="CustomValidator1_OnServerValidate"   
       ControlToValidate="txtDOB" 
       ErrorMessage="Age must be grater than 16 years"  >
</asp:CustomValidator>

and here is the event

protected void CustomValidator1_OnServerValidate(object source, ServerValidateEventArgs args)
    {
        DateTime todayDate = System.DateTime.Now;
        DateTime textDOB = Convert.ToDateTime(txtDOB.Text);

        DateTime total = todayDate.AddYears(-16);
        if (textDOB <= total)
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }
    }

Upvotes: 1

Views: 139

Answers (1)

Jahangeer
Jahangeer

Reputation: 478

Place AutopostBack="True" it will become something like this

  <asp:TextBox ID="txtDOB" AutoPostBack="true" runat="server" CssClass="textbox_width_height" placeholder="DD/MM/YYYY" CausesValidation="true"></asp:TextBox>

Hope it helps

Upvotes: 2

Related Questions