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. Ho开发者_运维问答pe this makes sense.
Corey
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
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?.
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
精彩评论