In
case we want to highlight the textbox or change the background color of the control that does not pass the validation check, then we can use the following:
Enter
Name:
<asp:TextBox ID="TextBox1" runat="server" Width="301px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" EnableClientScript="False" ErrorMessage="RequiredFieldValidator" Font-Bold="True" ForeColor="#6600CC">Please dont leave blank</asp:RequiredFieldValidator>
</div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Register" />
Note:
The following
property of the RequiredFieldValidator must be set to:
EnableClientScript="False"
Also we need to capture the following event. This will help in giving access to collection of all the validators used on the WebForm. We can iterate through the same and get the control on which validation occurred.
Code Behind File:
protected void Page_PreRender()
{
foreach (BaseValidator valControl in Page.Validators)
{
WebControl assControl = (WebControl)Page.FindControl(valControl.ControlToValidate);
if (!valControl.IsValid)
assControl.BackColor =
System.Drawing.Color.Yellow;
else
assControl.BackColor =
System.Drawing.Color.White;
}
}
Comments