The problem is that Firefox counts newline as "1"(\n) character while Chrome count them as "2"(\r\n)
This is what I get in a textarea
with maxlength=10
:
This are 10 charcters for Firefox
1234
5
6
7
This are 10 charcters for Chrome
1234
5
6
The problem comes when trying to validate the form. If I have for example the following text
012345
678
In Firefox the validation passes and the data is saved, but when I try to do the same in Chrome it shows a warning, and prevents it from sending the form. "Please shorten this text to 10 characters or less(you are currently using 11 characters)".
I think this validation messages are new in Chrome or at least I haven't see them before
Here is an JSFiddle example. To reproduce it in Chrome, you should write a string with 10 charcters then delete 1 and press enter to add a new line.
Here is an example of how JavaScript counts JSFiddle length count with js.
Don't know which one is the correct value for new line (1 or 2). But since the database (Postgres in my case) and JavaScript consider it as "1" character, I would like to know if there is a way to make Chrome to do the same.
I didnt find any solution to make the maxlength atribute to work the same way in all browsers, and I think is because its relative new. So I decided to go for javascript.
Googling a little I found this jQuery Max Length plugin that works great just adding a few lines. Is available under the MIT licence. And counts newlines as it should be (2 characters)
It has some parameters to set the maxlength, feedback text, background change when full, between others. The website has very good documentation and a lot of examples.
It's highly customisable, for example here is mine
This is the only code I used plus some css.
<script type="text/javascript" src="jquery.plugin.js"></script>
<script type="text/javascript" src="jquery.maxlength.js"></script>
<script>
$(function() {
$('.t_tresc').maxlength({
showFeedback: true,
feedbackText: '{c} / {m} max.',
overflowText: '{c} / {m} max!',
feedbackTarget: '#targetFeedback$name',
max: $max_length,
truncate: false,
onFull: null
});
});
</script>
来源:https://stackoverflow.com/questions/22016511/different-maxlength-validation-of-textarea-with-newlines-in-chrome-and-firefox