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:
- Define the max length
- 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)
- Replace content with new limited content
- 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.
For Unix, it is only \n, for old mac it will be \r as new line characters.
Replace \r to emptiness on the server side.