Home > AJAX, ASP.NET, C#, jQuery > Change Background Color of Invalid Controls with ASP.NET Validators

Change Background Color of Invalid Controls with ASP.NET Validators

Chris posted an excellent article explaining how to change background color of invalid controls (with ASP.NET Validators). In his article, the code loops through each validator in Page_Validators (it’s a global array in Javascript), finds the control to validate (ctrl.controltovalidate) of the validator, changes the background color of the control if the valiator is in invalid mode (ctrl.isvalid == false).

As the updates of validators only happens when the form is submitted, but I need a bit more – I want the updates trigger whenever the user makes change to the controls (type text in the text box, change option in the select box, etc).  Using bind() function in jQuery will do the trick.

Here is the code:

<script type=”text/javascript”>

var g_BackgroundColor = “#FFAAAA”;

jQuery(document).ready(function() {

for (var i = 0; i < Page_Validators.length; i++) {

var validator = Page_Validators[i];

if (validator.controltovalidate) {

BindValidatorsForChecking(validator.controltovalidate);

}

}

});

function OnUpdateValidators() {

for (var i = 0; i < Page_Validators.length; i++) {

var validator = Page_Validators[i];

// *** For each validator, find its associated control, then check its valid status

if (validator.controltovalidate) {

var control = document.getElementById(validator.controltovalidate);

if (control != null) {

control.style.backgroundColor = CheckValidatorsForControl(control) ? : g_BackgroundColor;

// *** Bind to check valid status

BindValidatorsForChecking(validator.controltovalidate);

}

}

}

}

// *** Check all validators for a control

function CheckValidatorsForControl(control) {

for (var i = 0; i < control.Validators.length; i++) {

if (!control.Validators[i].isvalid) {

return false;

}

}

return true;

}

// *** Bind to check valid status

function BindValidatorsForChecking(controlID) {

jQuery(“#” + controlID).bind(“blur focus mouseout mouseleave”, function(e) {

this.style.backgroundColor = CheckValidatorsForControl(this) ? : g_BackgroundColor;

});

}

</script>

In the code behind, you will need to hook the updates when the form is submitted as well:

Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), “OnUpdateValidators_Key”, “OnUpdateValidators();”);

About these ads
Categories: AJAX, ASP.NET, C#, jQuery Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: