Skip to content Skip to sidebar Skip to footer

Why Validatorvalidate() Validates All The Requiredfieldvalidator Controls On The Page?

In following code Why ValidatorValidate(v) validates all the RequiredFieldValidator controls on the page? It should execute only RequiredFieldValidator1 not RequiredFieldValidator2

Solution 1:

You need to return something from check(), otherwise, it's running it, and then passing through and doing the normal page validation.

After calling ValidatorValidate(), you can check if the validator isvalid

functioncheck() {

        var v = document.getElementById("<%=RequiredFieldValidator1.ClientID%>");
        ValidatorValidate(v);
if (v.isvalid)
     returntrue;
elsereturnfalse;
}

You did have an extra } in there as well.

You also need to throw in a return for the OnClientClick

<asp:ButtonID="Button1"runat="server"OnClientClick="return check()"Text="Check" />

Solution 2:

This happens because once you click the Button, it causes validation of all of them on postback. You'll need to group them by ValidationGroup or use return false; from check() to stop the postback.

Alternatively you could also replace the RequiredFieldValidator with CustomValidator and do conditional checks based on your needs.

If you REALLY want to do client side validator handling, check out http://msdn.microsoft.com/en-us/library/yb52a4x0.aspx#ClientSideValidation_ClientValidationObjectModel

This page has details on Client Validation Object Model which has a few JavaScript functions to handle conditional evaluation. Check out Validation event for asp net client side validation for an example of what one person was doing along these lines.

What are you trying to do specifically? Someone can probably help you get the correct setup.

Solution 3:

Your script is malformed.

<head><scripttype="text/javascript">functioncheck() {
             var v = document.getElementById("<%=RequiredFieldValidator1.ClientID%>");
             ValidatorValidate(v);
         }
   </script></head>

In your version you are getting a javascript error that the function check is not defined.

The second validator gets also triggered because Validator always are triggered before postback and your function check is called on a submit-button. Both validators would validate anyway even without your explicit call on ValidatorValidate.

If you don't want to postback onclick, use a HtmlButton instead:

<inputtype="button" onclick="check()" value="Check" />

Post a Comment for "Why Validatorvalidate() Validates All The Requiredfieldvalidator Controls On The Page?"