Friday, June 10, 2005

A Day Full Of "Features"

If you have been reading my blog for long, you know that I have had quite a few run ins with Microsoft's Validation Framework in .NET. Well, it reared it's ugly head again today.

I created some javascript that I wanted to fire on a text input when its value changed. The javascript that I wrote took the value of the text input and formatted it. In addition, on this same text input I created a custom validator, with client-side validation enabled. I created the needed javascript for the client-side validation. I open my page and begin to do a little testing. This is when I find the "feature".

Opening WebUIValidation.js (Microsoft's javascript library that makes all of the client-side validation of controls possible), I find the following snippet:

var ev;
if (control.type == "radio") {
    ev = control.onclick;
} else {
    ev = control.onchange;
}
if (typeof(ev) == "function" ) {  
    ev = ev.toString();
    ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
}
else {
    ev = "";
}
var func = new Function("ValidatorOnChange(); " + ev);
if (control.type == "radio") {
    control.onclick = func;
} else {  
    control.onchange = func;
}


Microsoft hooks their validation in so that it is called BEFORE any custom javascript that you may add to the onchange event of a control. Had they simply appended their validation function, their end would function as always, and developers would get expected results. In my case, it just so happened that the client-side javascript I added formatted the value in a way that made it valid. So, in my case, I enter some text, press the tab key, Microsoft's validation function fires, says that the entered text is invalid. Then, my custom formatting javascript fires, and the text is formatted. However, the validation is not performed again since the onchange doesn't fire when text is altered programatically. So, I have valid data, but the invalid message is still showing. Even worse, I can press the submit button, and it fires, since the data is actually valid. Very confusing for an end-user.

No comments: