Count textarea characters tricky issues.

Recently, from one of my projects, I faced the very interesting issues about characters count in the textarea. The purpose is to limit user inputs and had certain max character length, the max length value will be invoked from hibernate java bean column length, which will be consistency with user input and database storing. But issues occurred.

Now look at the scenario and logic to limit user input based on the max length, this will be done from jQuery:

  1. Define the max length
  2. Define keyup event, if the key is up/released, the event will be fired, and check whether the whole content length is bigger than the max length
    • if is bigger than max length, substring(0, maxlength)
  3. Replace content with new limited content
  4. submit to the server to store into DB


OS: windows XP

Browser: IE, Firefox, Chrome, etc

I try to paste texts copy paste from words or other editors into textarea. The text length is definitely over the max length and the input text is replaced with substring(0, maxlength).

Everything from front-end is quite good, it shows the warning, subtracts the input string and equals the max length.

Now I submit it. It fails to store into the database, and throws com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column. The limited length on the textarea is exactly the same with the table column length, it should not be a problem to store characters. But WHY?


From my research, it relates with new line characters.

Javascript detemins \n as new line character. But when you try to submit and post your text, the \n will be changed to \r\n and this only happend on Windows OS.

For Unix, it is only \n,  for old mac it will be \r as new line characters.

When we use javascript to validate the length it shows new line as one single character. However, when submit, the new line character will be doubled because it contains \r\n as two characters.


Replace \r to emptiness on the server side.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s