I've got a JSP page with a piece of Javascript validation code which limits to a certain amount of characters on submit. I'm using a <textarea>
so I can't simply use a length attribute like in a <input type="text">
.
I use document.getElementById("text").value.length
to get the string length. I'm running Firefox 3.0 on Windows (but I've tested this behavior with IE 6 also). The form gets submitted to a J2EE servlet. In my Java servlet the string length of the parameter is larger than 2000!
I've noticed that this can easily be reproduced by adding carriage returns in the <textarea>
. I've used Firebug to assert the length of the <textare>
and it really is 2000 characters long. On the Java side though, the carriage returns get converted to UNIX style (\r\n
, instead of \n
), thus the string length differs!
Am I missing something obvious here or what ? If not, how would you reliably (cross-platform / browser) make sure that the <textarea>
is limited.
JavaScript does not return the length but rather returns the code units occupied by the string. It uses the UTF-16 string formatting methods to store characters. This essentially means that the characters in your string are encoded into a 16-bit long binary number before being stored.
The length of a string in JavaScript can be found using the . length property. Since . length is a property it must be called through an instance of a string class.
The Java length method is used with the array class. The Java length property returns the size of an array. The Java length method returns the number of characters in a text String. The Java length method must have round brackets at the end.
The Java String length() method is a method that is applicable for string objects. length() method returns the number of characters present in the string. The length() method is suitable for string objects but not for arrays. The length() method can also be used for StringBuilder and StringBuffer classes.
This isn't really a JavaScript (or Java) problem - both layers report an accurate length for the string they are dealing with. The problem in your case is that the string gets transformed during the HTTP transmission.
If you absolutely must ensure that the string doesn't exceed a certain length, you can mimic this transformation on the client by replacing every instance of "\n" with "\n\r" - but only for length verification purposes:
textarea.value.replace(/\n/g, "\r\n").length
Do you particularly care which line-endings are used? Why not just make the Java convert "\r\n" to "\n"? (Note that "\r\n" is the Windows style; "\n" is the Unix style.)
Alternatively, do the reverse when checking the length within the JavaScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With