Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...