[RESOLVED] changing backcolor of textbox when input is invalid......

Hello I have an ASP.net page with two textboxes where the user types in input.  I applied a requiredfieldvalidator to both textboxes as well.  However, I also want the textboxes to change to a backcolor of red if the form is invalid when the user clicks the button to submit the input.  I tried this code below in tthe button click event, but doesnt work...

If Page.IsValid = False Then
            txtCosts.BackColor = Drawing.Color.Red
            txtRevenue.BackColor = Drawing.Color.Red
        End If

How else can I change the Backcolor of the textboxes when the input is invalid.......

hi bababooey check this link here i explain clearly how to change the textbox background colorwhenever validation fails using asp.net


You can do such validations client side.

Ofcourse the page needs to validated on the server too.

Here's an example  

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <script language="javascript" type="text/javascript">
        function abc(){
            if (typeof (Page_ClientValidate) == 'function') {
            if (!Page_IsValid) {
                return false;
            return true;

        function ChangeBackColor() {
            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 (!CheckIfValid(ctrl)) {
                    ctrl.style.background = 'red';
            else {
                ctrl.style.background = '';

        function CheckIfValid(control) {
            for (var i = 0; i < control.Validators.length; i++) {
                if (!control.Validators[i].isvalid) {
                    return false;
            return true;
      <asp:TextBox ID="TextBox1" runat="server"  ></asp:TextBox>
      <asp:RequiredFieldValidator ID="Req1" runat="server" ErrorMessage="Required" Display="Dynamic"  ControlToValidate="TextBox1" ForeColor="Red"  Text="text1 Required" ValidationGroup="VGrp1"></asp:RequiredFieldValidator>
      <br />
      <asp:Button ID="btnsubmit"  runat="server" Text="Submit" OnClientClick="abc();"  onclick="btnsubmit_Click"/>

protected void btnsubmit_Click(object sender, EventArgs e)
        if (!Page.IsValid)


If you are interested learning more on client side validation


thoughts on "[RESOLVED] changing backcolor of textbox when input is invalid......"

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>