Forum Moderators: open
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ForeColor="" InitialValue="" ControlToValidate="txtEmail" ID="txtEmail1" runat="server" ErrorMessage="Required Field" Display="Dynamic" /></div>
<asp:TextBox ID="txtEmail" runat="server" />
<asp:RequiredFieldValidator EnableClientScript="false" ID="rfvEmail" runat="server" ControlToValidate="txtEmail" ErrorMessage="*" />
<br />
<asp:TextBox ID="txtOther" runat="server" />
<asp:RequiredFieldValidator EnableClientScript="false" ID="rfvOther" runat="server" ControlToValidate="txtOther" ErrorMessage="*" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
protected void Button1_Click(object sender, EventArgs e)
{
// First reset the styling of all TextBox controls
foreach (Control c in form1.Controls)
{
if (c is TextBox)
{
TextBox tb = (TextBox)c;
tb.Attributes.Clear();
}
}
// Now check for invalid TextBoxes
if (!Page.IsValid )
{
foreach (Control c in form1.Controls)
{
if (c is RequiredFieldValidator)
{
RequiredFieldValidator rfv = (RequiredFieldValidator)c;
if (!rfv.IsValid)
{
// Try to find the matching TextBox control (the ControlToValidate)
TextBox tb = (TextBox)form1.FindControl(rfv.ControlToValidate);
if (tb != null)
{
tb.Attributes.Add("style", "background-color:#ff0");
}
}
}
}
}
}