Introduction: In this article i will
explain how to highlight asp.net controls like textbox and dropdownlist by
changing the border color and background color on validation failure e.g.
RequiredFieldValidator failure error that occurs when control like textbox is
left blank or dropdownlist item is not selected in asp.net using javascript.
In Head
tag of Page, create a javascript function that
will traverse through all the validations control present on the page and highlight the control by coloring the border to
red if the controls are left blank.
<script type="text/javascript">
function validateAndHighlight()
{
for (var i = 0; i < Page_Validators.length; i++) {
var val =
Page_Validators[i];
var ctrl =
document.getElementById(val.controltovalidate);
if (ctrl != null &&
ctrl.style != null) {
if (!val.isvalid)
{
ctrl.style.borderColor = '#FF0000';
ctrl.style.backgroundColor = '#fce697';
}
else {
ctrl.style.borderColor = '';
ctrl.style.backgroundColor = '';
}
}
}
}
</script>
Design Section:
<fieldset style="width:280px;">
<legend><strong>Highlight
control on validation failure</strong></legend>
<table>
<tr>
<td>
Emp Name
</td>
<td>
<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmpName" runat="server"
ControlToValidate="txtEmpname" Display="Dynamic" ErrorMessage="*"
ForeColor="Red" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Salary
</td>
<td>
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvSalary" runat="server"
ControlToValidate="txtSalary" Display="Dynamic" ErrorMessage="*"
ForeColor="Red" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Department
</td>
<td>
<asp:DropDownList ID="ddlDept" runat="server">
<asp:ListItem Value="0">-- Select
Department --</asp:ListItem>
<asp:ListItem>HR</asp:ListItem>
<asp:ListItem>IT</asp:ListItem>
<asp:ListItem>Sales</asp:ListItem>
<asp:ListItem>Production</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvDept" runat="server"
ControlToValidate="ddlDept" Display="Dynamic" InitialValue="0"
ErrorMessage="*" ForeColor="Red" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Sumbit" />
</td>
</tr>
</table>
</fieldset>
Asp.Net C# code to highlight textbox and dropdownlist control on
validation failure
In the
code behind file write the code on page load as:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "validateAndHighlight();");
}
Asp.Net VB code to highlight textbox and dropdownlist control on
validation failure
In the code behind file write
the code on page load as:
Protected Sub Page_Load(sender As Object, e As EventArgs)
Page.ClientScript.RegisterOnSubmitStatement(Me.[GetType](), "val", "validateAndHighlight();")
End Sub
0 comments:
Post a Comment