在asp.net中不为文本框触发自定义验证器验证

时间:2015-07-09 07:04:53

标签: asp.net validation c#-4.0

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

这是事件

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;
        }
    }

1 个答案:

答案 0 :(得分:2)

放置AutopostBack =&#34; True&#34;它会变成这样的东西

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

希望有所帮助