| Trouble viewing this page? Give Feedback .
Try my blog on: Ajax Version

Thursday, September 03, 2009

javascript maxlength for textarea with \r\n breaks in java (esp Firefox)

Textareas allow new lines to enter. These are represented by \n (1) or \r\n (2) characters. But when you save to DB you have a limit to certain length of chars. There is no maxlength attribute in HTML that will stop you from entering data. This is generally acomplished by Javascript. You do a onkeyup hook and stop event or trim after textarea.value.length > maxlength. There are many other solutions out there.. But..

Here is the problem that most of those solutions overlook, How do you deal with the count on \n and \r\n representations. Lets first see how it matters. If the text entered has new lines, the length is calculated differently in Firefox and IE. When you enter a Text like

You expect the textarea.value.length to be 11. (10 chars + new line).On the backend, however, java would recieve it as 12 chars (10 chars + \r\n) (this is irrespective of FF or IE). So you are effectively saving 12 chars to DB.

Worse yet, IE seems to figure textarea.value.length as 12 (10 chars + \r\n)(one thing that it ever got right?). FF treats it only (10 chars + new line) (like you originally expected). All this descrepency can be disturbing when you want to consistently save chars of maxlength correctly to database.

So here is a javascript function that will correctly calculate the length of textarea value.
taLength = function(str) {
 if (!str)
  return 0;

 var lns = str.match(/[^\r]\n/g);

 if (lns)
  return str.length + lns.length;

  return str.length;
This will handle length count issues for display purposes. You can warn and disallow users from entering more characters.

© 2000