Search code examples
asp.netvalidation-controls

Is it possible to use ASP.NET validation controls when I need to modify HTML when validation fails?


Let's say that I have the following HTML for a text box on an ASP.NET page:

<div class="myClass">
    <asp:TextBox ID="txtMyTextBox" runat="server"></asp:TextBox>
</div>

It is easy enough to add a required field validator to this page like this.

<asp:RequiredFieldValidator ID="valMyTextBox" runat="server" ControlToValidate="txtMyTextBox" ErrorMessage="My Text Box is required."></asp:RequiredFieldValidator>

But I need to modify the HTML slightly if this text box fails validation. I need to add a CSS class to the DIV. So if the user leaves this field blank I need the HTML to look like this:

<div class="myClass error">
    <asp:TextBox ID="txtMyTextBox" runat="server"></asp:TextBox>
</div>

Is this possible? I can't figure out if there is a way to write code behind that only fires if this particular validator control fails validation or something. I know I can write code that runs when the entire page is not valid. But I just want this code to run when this validator returns invalid. Hope this makes sense.

Corey


Solution

  • Actually I found the answer in a different StackOverflow question. You can see it here: How do I add an additional CSS class on a surrounding DIV for failed form validation?.