1

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

Corey Burnett
  • 7,312
  • 10
  • 56
  • 93
  • this could be solved by javascript or any other scripting languages are you familiar with them? – Laurence Burke Mar 16 '11 at 19:41
  • Yes, of course there are lots of different ways to solve this. Specifically I am trying to figure out if there is a way to solve this using ASP.NET validation controls. – Corey Burnett Mar 16 '11 at 19:44
  • checkout this answer it might help http://stackoverflow.com/a/12806045/696978 – gsimoes Aug 16 '13 at 22:46

3 Answers3

0

OK I think this might help even though I am not to sure on the exact ways to do this

<div class=<%Response.Write(validateTextBox())%>>

that function which would be on the server that you would call to change the name of the class depending on the text box

Laurence Burke
  • 2,348
  • 14
  • 26
0

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?.

Community
  • 1
  • 1
Corey Burnett
  • 7,312
  • 10
  • 56
  • 93
  • 1
    This requires a postback. An alternative is to create a custom validator, to which you can specify both a client-side javascript function which can do the client validation, and you can provide a backend function that will run when post-back occurs – Prescott Mar 16 '11 at 22:01
0

Another way to do it without Postback is to override the default asp.net validation scripts. I posted an example here: https://stackoverflow.com/a/9857696/618044

Community
  • 1
  • 1
Jeremy A. West
  • 2,162
  • 4
  • 27
  • 40