简体   繁体   中英

ASP.NET custom validator is not working

I've done everything this page told me to do, but it's not working, i've seen people posting about this problem and being told to add a required field validator, i've done that, still not working.

Here's the client side part

                <asp:CustomValidator 
                    ID="CustomValidator1" 
                    runat="server" 
                    ControlToValidate="TextBoxUsername" 
                    ErrorMessage="Username already exists" 
                    OnServerValidate="CustomValidator1_ServerValidate" 
                    ValidateEmptyText="True" <!--tried without this line-->
                    ValidationGroup="form">  <!--tried without this line-->
                </asp:CustomValidator>

Here's the C# server side code

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){
            args.IsValid = false;
        }

looks pretty simple, right ? it should keep appearing all the time, right ? well, it only appears at the beginning and then disappears forever and that's because I have this line in the page_load() method, but i also have it in the button_click() method.

Page.Validate();

First up, remove the validation group, and add in Text :

<asp:CustomValidator 
    ID="CustomValidator1" 
    runat="server" 
    ControlToValidate="TextBoxUsername" 
    ErrorMessage="Username already exists" 
    Text="Username already exists"
    OnServerValidate="CustomValidator1_ServerValidate" 
    ValidateEmptyText="True">
</asp:CustomValidator>

ErrorMessage will show in a ValidationSummary control and Text should show where the validator is.

Update the button to cause validation (I believe true is the default anyway, but lets be explicit):

Then check if the page is valid after click, Page.Validate doesn't need to be called as it will be automatically for things that CauseValidation .

protected void Button1_Click(object sender, EventArgs e)
{ 
   if (Page.IsValid)
   {
       // Do Cool Stuff
   }
}

Additionally, drop a breakpoint on the click method when checking it as you don't have any client side wiring (eg ClientValidationFunction="somejsfunction" on the validator) so you will only hit this code when you get through to server side validation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM