Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Validator not working for textbox

I am learning how to use custom validator for server-side validation, but I can't seem to get it working. Whenever I click on the button, with the textbox empty, the error message does not show up. What am I doing wrong?

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1"
     OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="ValidateGp"
     ErrorMessage="This is a custom error validator" runat="server"/>

<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="ValidateGp"/>

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    if (args.Value.Equals(string.Empty))
    {
        args.IsValid = false;
    }
    else
    {
        args.IsValid = true;
    }
}
like image 979
coffeeak Avatar asked Jan 22 '26 16:01

coffeeak


1 Answers

You missed ValidateEmptyText="true" for

<asp:CustomValidator ID="CustomValidator1"
                    ValidateEmptyText="true" runat="server" ValidationGroup="ValidateGp" ErrorMessage="This is a custom error validator" ControlToValidate="TextBox1" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
like image 121
vml19 Avatar answered Jan 24 '26 04:01

vml19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!