this.Blog.Find(entry => entry.IsHelpful);
 Wednesday, March 26, 2008
Changing a control's CSS class name during validation

So I'm converting an ASP.Net prototype that was written entirely in VB Script (don't ask) to C#.  As part of the conversion, I am putting in ASP.Net validation controls on all the input fields in the application.  I was showing off my progress to the graphics designer, and he pointed out that he wanted to dynamically change the CSS class on the input field control that was being validated if it failed validation.  Hmm, I can set the CssClass attribute on the validation control, but I couldn't find anywhere to automatically change the CSS class name on the actual control being validated.

I *could* write custom validators for each input control and change the class name in the javascript validation function, but that seemed like too much work.  So I thought to myself, surely there is some way to add an event listener to the DOM on the validation control to see if it changed it's display attribute.  After some researching, I got it to work.

<head runat="server">
    <title>Test Page</title>
    <style type="text/css">
      .error
      {
        border: solid 1px red;
        background-color: Yellow;
      }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <div>
            <asp:TextBox ID="txtBox" runat="server" />
            <asp:RequiredFieldValidator ID="reqField" runat="server" ControlToValidate="txtBox"
                Display="Dynamic" EnableClientScript="true" ErrorMessage="* Required"
SetFocusOnError="true" />
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
        </div>
        <script type="text/javascript" language="javascript">
    function pageLoad() {
        $addHandlers($get('<%= this.reqField.ClientID %>'),
                     { 'DOMAttrModified' : changeTextBoxClass,
'propertychange' : changeTextBoxClass });
    }
    function changeTextBoxClass(eventName) {
        $get('<%= this.txtBox.ClientID %>').className =
            $get('<%= this.reqField.ClientID %>').style.display != 'none' ? 'error' : '';
    }
        </script>
    </form>
</body>
</html>

DOMAttrModified is not supported in IE (shocking!!!) - onpropertychange is the IE equivalent.  Basically, whenever the ASP.Net validators fire and change the "display" attribute on their enclosing <span> tags, I added an event handler that will dynamically set the CSS class on the corresponding input control.  Notice in the example above that I'm using the ASP.Net Ajax library to make my life easier.

Before validation:

image

 

And after the "Submit" button is clicked:

image


Kick it on DotNetKicks.com
Wednesday, March 26, 2008 9:14:38 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Ajax | ASP.Net

Comments are closed.