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

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.


Solution 1:

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>

Solution 2:

You could use the following script:

<script>

    $(function(){
        if (typeof ValidatorUpdateDisplay != 'undefined') {
            var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;

            ValidatorUpdateDisplay = function (val) {
                if (!val.isvalid) {
                    $("#" + val.controltovalidate).css("border", "2px solid red");
                }

                originalValidatorUpdateDisplay(val);
            }
        }
    });

</script>

This code decorates the original ValidatorUpdateDisplay function responsible for updating the display of your validators, updating the controltovalidate as necessary.

Hope this helps,

Solution 3:

I think you would want to use a Custom Validator and then use the ClientValidationFunction... Unless it helpfully adds a css class upon fail.