Search code examples
asp.netwebforms

How do I highlight a textbox border red when it is required?


What property do I use on the required field validator control to make the textbox red if there is a validation error?

Here is my code:

<asp:Label ID="lblFirstName" runat="server" AssociatedControlID="txtFirstName" Text="First Name:" CssClass="reg-labels" />
<br />
<asp:TextBox ID="txtFirstName" runat="server" CausesValidation="true" MaxLength="60" CssClass="standard_width"/>
<asp:RequiredFieldValidator ControlToValidate="txtFirstName" runat="server" ID="valFirstName" ValidationGroup="grpRegistration" ErrorMessage="First Name is required." Text="*" />

Solution

  • ASP.Net web forms internally uses a Javascript frameworka located at aspnet_client\{0}\{1} folder to handle the validation, etc. They are basically determined from the property ClientScriptsLocation

    Try overriding the default framework function by keeping it in your page includes additional line to set the control_to_validate color

    document.getElmentById(val.controltovalidate).style.border='1px solid red';

    <asp:TextBox ID="txtFirstName" runat="server" CausesValidation="true" MaxLength="60"
        CssClass="standard_width" />
    <asp:RequiredFieldValidator ControlToValidate="txtFirstName" runat="server" ID="valFirstName" ValidationGroup="grpRegistration" ErrorMessage="First Name is required." Text="*" />
    <asp:Button Text="Super" ID="btnSubmit" CausesValidation="true" runat="server" />
    

    JS

    <script type="text/javascript">
        function ValidatorUpdateDisplay(val) {
            if (typeof (val.display) == "string") {
                if (val.display == "None") {
                    return;
                }
                if (val.display == "Dynamic") {
                    val.style.display = val.isvalid ? "none" : "inline";
                    return;
                }
    
            }
            val.style.visibility = val.isvalid ? "hidden" : "visible";
            if (val.isvalid) {
                document.getElementById(val.controltovalidate).style.border = '1px solid #333';
            }
            else {
                document.getElementById(val.controltovalidate).style.border = '1px solid red';
            }          
        }
    </script>