Change background color of a control when validation fails in ASP.NET:
This article explains how to change background color of a control when Validation fails in a webpage using ASP.NET.
Defauls.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
body
{
font-family: Verdana;
font-size: 12pt;
}
.Error
{
background-color: Red;
border: solid 1px Red;
}
</style>
</head>
<body>
<form id="FormControl" runat="server">
<div>
UserName:
<asp:TextBox ID="txtUname" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv2" runat="server" ControlToValidate="txtUname" ErrorMessage="Please enter username">
</asp:RequiredFieldValidator>
<br /><br />
Password:
<asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv3" runat="server" ControlToValidate="txtPwd" ErrorMessage="Please enter password">
</asp:RequiredFieldValidator>
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>
</form>
<script type="text/javascript">
function WebForm_OnSubmit()
{
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false)
{
for (var i in Page_Validators)
{
try
{
var control = document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid)
{
control.className = "Error";
}
else
{
control.className = "";
}
}
catch (e) { }
}
return false;
}
return true;
}
</script>
</body>
</html>Output

After validation fails


Kumar SambhavPosted Sep 13, 2012, 7:32 AM
Very Nice Programming.........