Share via


Customizing ASP.NET Validators without using the CustomValidator Control

This isn’t a SharePoint tip, per se, but it is an interesting way to expand on what the default RequiredFieldValidator control does for you.

We already had validation in our custom pages using the RequiredFieldValidator control, and it was working well, however, our customer wanted the behavior to be different than the default of displaying an asterisk next to required fields.  Instead, it needed to highlight the required fields by shading them a light red (I think that’s called pink… anyway…).  My first thought was to change to use the CustomValidator control, which would allow us to have custom client-side script.  However, that would mean that I would need to implement the validation logic in JavaScript for the client and again in C# for the server.  The standard RequiredFieldValidator class does both client and server-side validation automatically, which is nice.

So, instead, I remembered that you can mess with function pointers in JavaScript and essentially override whatever functions you want.  With a little poking around using IE 8’s developer add-in, I found that the function I wanted to “override” was the ValidatorUpdateDisplay function.  Within this function, I could add in the code to highlight the field any way I wanted.

So, here’s what the JavaScript looks like.

 var Original_ValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay = function(val) {
    Original_ValidatorUpdateDisplay(val);
    var valControl = document.getElementById(val.controltovalidate);
    if (valControl) {
        valControl.style.backgroundColor = val.isvalid ? 0xFFFFFF : 0xFFE0D6;
    }
}

Place this within your <form> section in a <script> block and your new function will get called anytime there is validation done (I put it in the master page for our custom forms).  Change the code in the “if (valControl)…” block to do whatever highlighting you want.  Note that the effect you get from this is that the fields that don’t pass validation will be shaded light red, but as soon as the user enters valid data and the field loses the focus, it will change it back to a white background, giving the user instant visual validation.

This code does two things:

1. It saves off the function pointer of the original ValidatorUpdateDisplay function into a variable called Original_ValidatorUpdateDisplay.

2. It replaces the original function pointer with a new function pointer (defined in-line as an anonymous method).

This way, the new method can call the original method and not have to reproduce all of its code.

Comments

  • Anonymous
    October 12, 2010
    This might be the coolest thing I've seen in a while, purely from a standpoint of usefulness...  Thanks a lot!