简体   繁体   中英

Custom compare validator

I've got an assignment for school in which two textboxes have to be the same, exactly the same as using a compare validator but instead we have to use a custom validator.

The code I used so far is:

protected void CustomValidator1_ServerValidate1(object source, ServerValidateEventArgs args)
{
    if (TextBox2.Text == TextBox3.Text)
    {
        args.IsValid = true;
    }
    else 
    {
        args.IsValid = false;
    }

}

and in ASP.NET

<asp:CustomValidator ID="CustomValidator1" runat="server" 
ErrorMessage="The second and third haven't got the same input."
onservervalidate="CustomValidator1_ServerValidate1" 
ValidateEmptyText="True" ValidationGroup="Custom"></asp:CustomValidator>

But when I debug the webform nothing shows up when I fill in two different inputs.

The controls won't be validated until you attempt to submit the form to the server; they won't be validated as soon as they are edited.

You can specify AutoPostback to be true to cause the form to be submitted to the server every time the textboxes are edited, but that's likely to cause its own set of problems.

To have the form be validated entirely on the client, without posting to the server, you'll need to write that JavaScript code yourself, rather than a custom validator.

To enable client side (before posting back) validation with a CustomValidator, you must set the ClientValidationFunction to some JavaScript.

Something like:

<asp:CustomValidator ID="CustomValidator1" runat="server" 
ErrorMessage="The second and third haven't got the same input."
onservervalidate="CustomValidator1_ServerValidate1" 
ClientValidationFunction="CustomValidator1_ClientValidate1"
ValidateEmptyText="True" ValidationGroup="Custom"></asp:CustomValidator>

<script type="text/javascript">
    function CustomValidator1_ClientValidate1(source, arguments) {
       if (/* validation code */) {
         arguments.IsValid = true;
       } else {
         arguments.IsValid = false;
       }
    }
</script>

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