Pages

Saturday, 19 March 2016

Change Background and Border Color of Invalid Controls when Validation fails in ASP.Net

In this article I will explain how to change the background and border color of invalid controls when ASP.Net validator validation fails.
There are many methods available on internet but this one is one time coding effort and then it will simply work for all ASP.Net Validators
To start with you will need to add the below two items either to your Page or your Master Page in case you are using Master Pages.
1. StyleSheet
I have created a very small CSS class for the invalid controls to change their background and border colors. Simply place the CSS classes in your global CSS file or place it in the <headsection of your page
 
<style type="text/css">
    body
    {
        font-family:Arial;
        font-size:10pt;
    }
    .ErrorControl
    {
        background-color#FBE3E4;
        bordersolid 1px Red;
    }
</style>
 
2. JavaScript Method
In order to change the colors of invalid controls we will override the ASP.Net WebForm_OnSubmit which is an inbuilt ASP.Net JavaScript method. To make this method work you need to place it at the very end of the Page or Master Page just where <body> the tag ends i.e. above </body> tag.
 
<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 = "ErrorControl";
            } else {
                control.className = "";
            }
        } catch (e) { }
    }
    return false;
 }
 return true;
}
</script>
 
This is all you need to do and now all the ASP.Net validators in your ASP.Net Web application will automatically change the Background and Border colors of invalid controls when the validation fails.
Examples
Required Field Validator
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1"
    runat="server" ErrorMessage="Required"></asp:RequiredFieldValidator>
 
Custom Validator
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Required"
    ControlToValidate="TextBox2" ValidateEmptyText="true" ClientValidationFunction="Validate"></asp:CustomValidator>
<script type="text/javascript">
    function Validate(sender, args) {
        if (document.getElementById(sender.controltovalidate).value != "") {
            args.IsValid = true;
        } else {
            args.IsValid = false;
        }
    }
</script>
 
Screenshot
Change background and border color of invalid controls when asp.net validator fails using JavaScript
The above code has been tested in the following browsers

No comments:

Post a Comment