Archive

Archive for the ‘AJAX’ Category

Change Background Color of Invalid Controls with ASP.NET Validators

July 16, 2010 Leave a comment

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();”);

Categories: AJAX, ASP.NET, C#, jQuery Tags: , ,
Follow

Get every new post delivered to your Inbox.