Change Text Box Color using Required Field Validator. No Extender Controls Please

前端 未结 16 2143
广开言路
广开言路 2020-11-28 07:07

I need to change color of TextBox whenever its required field validator is fired on Clicking the Submit button

16条回答
  •  遥遥无期
    2020-11-28 07:47

    What you can do is register a Javascript function that will iterate through the global Page_Validators array after submission and you can set the background appropriately. The nice thing about this is that you can use it on all of your controls on the page. The function looks like this:

    function fnOnUpdateValidators()
    {
       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.background = '#FFAAAA';
             else
                ctrl.style.backgroundColor = '';
          }
       }
    }
    

    The final step is to register the script with the OnSubmit event:

    VB.NET:

    Page.ClientScript.RegisterOnSubmitStatement(Me.GetType, "val", "fnOnUpdateValidators();")
    

    C#:

    Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "fnOnUpdateValidators();");
    

    You'll maintain the proper IsValid status in all of your code behind and it can work with all of your controls.

    Note: I found this solution from the following blog. I just wanted to document it here in the event the source blog goes down.

提交回复
热议问题