Monday, January 05, 2015

C# and Javascript events

I tend to be creative when it comes to using the standard provided C# validation controls but there are cases where Javascript validation comes in handy. One of them is restricting the length of a textarea "control" or rather a Multiline Textbox.
After some trial and errors, as well as trying out some ideas found on the web, here's what I found to work best.
Define a Javascript function (directly in your .aspx page or as a linked Javascript file) as follows:
function checkSize(oSrc, maxLen){
if (oSrc.value.length > maxLen)
{
        alert ("Your comments should have a maximum of " + maxLen + " characters long.");
        oSrc.value = oSrc.value.substring(0, maxLen);
        oSrc.focus();
        return false;
}
On the control itself, there is nothing to do. However, to make the function fire up, you need to add the following code in the codebehind, in a section that will be called before the object is rendered*:
wObjectName.Attributes.Add("onkeyup", "checkSize(this, 255);");
* For DataGrid controls and the like, you need to issue a FindControl("wObjectName") before you can add attributes so you may need to do this in an onCreate method.Hope it helps someone.