Why ValidatorValidate() validates all the RequiredFieldValidator controls on the page?

jams picture jams · Oct 3, 2011 · Viewed 14.3k times · Source

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

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script type="text/javascript">
        function check() {

            var v = document.getElementById("<%=RequiredFieldValidator1.ClientID%>");
            ValidatorValidate(v);

        }
        </script>    
    </head>
    <body>
        <form id="form1" runat="server">
        <div>

            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox2"></asp:RequiredFieldValidator>
            <br />
            <asp:Button ID="Button1" runat="server" OnClientClick="check()" Text="Check" />

        </div>

        </form>
</body>
</html>

Answer

Doozer Blake picture Doozer Blake · Oct 3, 2011

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

function check() {

        var v = document.getElementById("<%=RequiredFieldValidator1.ClientID%>");
        ValidatorValidate(v);
if (v.isvalid)
     return true;
else
     return false;
}

You did have an extra } in there as well.

You also need to throw in a return for the OnClientClick

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