Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 366
Travis Collins Avatar asked Aug 19 '09 17:08

Travis Collins


3 Answers

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>
like image 177
TheVillageIdiot Avatar answered Oct 08 '22 20:10

TheVillageIdiot


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,

like image 23
gsimoes Avatar answered Oct 08 '22 21:10

gsimoes


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

like image 40
Tom Ritter Avatar answered Oct 08 '22 21:10

Tom Ritter