Thursday, April 30, 2009

Impose maxlength on textarea controls to avoid "String or binary data would be truncated" error

As we all know that you can restrict a text box to allow limited number of characters using maxlength attribute as shown below

<input id="tbName" maxlength="20" type="textbox" width="100"/>

(or)

<asp:TextBox ID="tbName" MaxLength="20" Width="100px" runat="server" />

It is very simple and easy to impose the maximum length constraint for text boxes.

But this is not the case for textarea /multiline text box controls. There is no straight way to do this. We don't have the maxlength attribute for html textarea control. This post explains how to add that support.

Please check the below javascript function imposeMaxLength(field,maxChars) which takes 2 parameters:
- field which is the textarea control itself
- maxChars to tell the function how many charaters to be allowed.

<script type="text/javascript">
function imposeMaxLength(field,maxChars)
{
if(field.value.length > maxChars)
{
field.value = field.value.substring( 0, maxChars );
alert( 'Textarea value can only be ' +maxChars + ' characters in length.' );
return false;
}
}
</script>

The function needs to be called in onkeypress event of the textarea control. Please see the below code to know how we should call the method imposeMaxLength in onkeypress event of the textareancontrol

<textarea id="tbDescription" onkeypress="imposeMaxLength(this, 512)" />

(or)

<asp:TextBox ID="tbDescription" TexMode="MultiLine" runat="server" onkeypress="imposeMaxLength(this, 512)" />

The above code renders a text area control and restricts the control not to allow more than 512 characters.

This is very useful when you have database fields with limited string length. We have faced many pronlems as the user was entering bulky data and the field doesn't support and hence throws the exception. After implementing this we were comfortable and there were no exceptions like String or binary data would be truncated.

0 comments: