Question

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;
    }
}
Was it helpful?

Solution

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>

OTHER TIPS

Alternatively to forcing an empty validation, as in some cases an empty TextBox is a valid (!), I suggest you trap the TextBox change event and force a Page.Validate() there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top