C# – asp.net custom validator not firing for textbox

asp.netccustomvalidatorvalidation

I have both a required field validator and custom validator for validating a texbox. The required field validator fires perfectly. I'm not able to get the custom validator to fire properly?

<asp:TextBox ID="txtPRI" runat="server" Width="295" /><br />

<asp:RequiredFieldValidator display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  runat="server" controltovalidate="txtPRI" errormessage="Please enter your PRI" />

 <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtPRI" onservervalidate="cusCustom_ServerValidate" Enabled="true" ValidateEmptyText="true" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  errormessage="The text must be exactly 8 characters long!" />

code behind

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        Response.Write("firing - test");
        Response.End();


        if (e.Value.Length == 8)
            e.IsValid = true;
        else
            e.IsValid = false;
    }

Best Answer

Check that you have the your CustomValidator property ValidateEmptyText set to true so that empty text will be validated. Then you will not need the RequiredFieldValidator anymore.

EDIT: I took your code and copy and pasted it into an empty project and it works as expected. There must be something you have not posted, or is posting incorrectly, that we are not aware of. Is there anything else that affects the button that is triggering the validation or the validation controls themselves?

EDIT: Here is the exact code (it's in a content page):

aspx page:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:TextBox ID="txtPRI" runat="server" Width="295" /><br />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  runat="server" controltovalidate="txtPRI" errormessage="Please enter your PRI" />  
    <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtPRI" onservervalidate="cusCustom_ServerValidate" Enabled="true" ValidateEmptyText="true" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  errormessage="The text must be exactly 8 characters long!" /> 
</asp:Content>

.cs page (empty Page_Load):

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{ 
    // put a break point here and it stops on it
    if (e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
}