Change textbox's css class when ASP.NET Validation fails

Travis Collins picture Travis Collins · Aug 19, 2009 · Viewed 39.7k times · Source

How can I execute some javascript when a Required Field Validator attached to a textbox fails client-side validation? What I am trying to do is change the css class of the textbox, to make the textbox's border show red.

I am using webforms and I do have the jquery library available to me.

Answer

TheVillageIdiot picture TheVillageIdiot · Aug 19, 2009

Here is quick and dirty thing (but it works!)

<form id="form1" runat="server">
      <asp:TextBox ID="txtOne" runat="server" />
      <asp:RequiredFieldValidator ID="rfv" runat="server" 
                                 ControlToValidate="txtOne" Text="SomeText 1" />
      <asp:TextBox ID="txtTwo" runat="server" />
      <asp:RequiredFieldValidator ID="rfv2" runat="server" 
                                 ControlToValidate="txtTwo" Text="SomeText 2" />
      <asp:Button ID="btnOne" runat="server" OnClientClick="return BtnClick();" 
                                         Text="Click" CausesValidation="true" />
    </form>
    <script type="text/javascript">
        function BtnClick() {
            //var v1 = "#<%= rfv.ClientID %>";
            //var v2 = "#<%= rfv2.ClientID %>";
            var val = Page_ClientValidate();
            if (!val) {
                var i = 0;
                for (; i < Page_Validators.length; i++) {
                    if (!Page_Validators[i].isvalid) {
                        $("#" + Page_Validators[i].controltovalidate)
                         .css("background-color", "red");
                    }
                }
            }            
            return val;
        }
    </script>