paek
paek

Reputation:

Changing a control's style based on validation (ASP.NET)

I've got a very simple form with the following troubled snippet:

<asp:Panel class="normal" ID="Panel1" runat="server">
 <strong><asp:Label ID="Panel1Error" class="error" Visible="false" runat="server"/></strong>

 <label for="TextBox1"><em>*</em> Don't leave this blank</label>
 <asp:TextBox ID="TextBox1" runat="server" />

 <asp:RequiredFieldValidator ID="TextBox1RFV" runat="server"
  ControlToValidate="TextBox1" ErrorMessage="This field cannot be blank."
  Display="None" />

    <--- other validators --->
</asp:Panel>

There are two things I want to do when the page fails validation:

  1. Change the style of Panel1 (to one which shows different colors to indicate an error). I was able to do this by calling Page.Validate in Page_Load, then iterating over Page.Validators, getting each validator's parent control, casting it to a Panel, then setting .CssClass Doesn't seem like a superb solution, but it got the job done - is there a better way?

  2. I want to take whatever validation error(s) are thrown and put them in the Panel1Error label, as well as set it to visible. This is where I am a bit baffled. I thought at first I could possibly specify the Label in which a validator writes its ErrorMessage, but I had no such luck. If I just toss the validator inside the Label, its formatting messes up the entire layout of the page, regardless of whether I directly assign it the 'error' CSS class or just leave it in the Label.

Just to clarify, in production, I would be doing this process for multiple Panels on a page, each with one form element, preventing me from calling the Panels explicitly and just saying Panel1.CssClass, etc.

Upvotes: 1

Views: 1196

Answers (2)

jrummell
jrummell

Reputation: 43067

  1. I would recommend a javascript solution. ASP.NET injects a global js variable called Page_Validators, which is an array of all of the validator spans on the page. I wrote about this on my blog. It's a different solution, but it should give you enough insight to get started.
  2. Use ValidationSummary controls with a ValidationGroup for each panel.

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

  1. Seems fine if it worked.

  2. Use a ValidationSummary control. Or you can inherit from the controls and override the render event.

Upvotes: 0

Related Questions