* (bug 29804) Fix byte-length-limited fields to check the length of to-be-added char...
authorBrion Vibber <brion@users.mediawiki.org>
Mon, 11 Jul 2011 17:53:52 +0000 (17:53 +0000)
committerBrion Vibber <brion@users.mediawiki.org>
Mon, 11 Jul 2011 17:53:52 +0000 (17:53 +0000)
Since the Unicode code point of the character being inserted is passed with the keypress event, we can simply turn it into a string and toss it into jquery.byteLength to calculate the length in bytes.

Also fixed a broken test case that had the wrong number of expected chars.

Note that this will probably still not work right in many circumstances -- pastes, anything dealing with selection, and it's entirely possible that individual 'keypress' events might be totally unreliable when dealing with funky input methods.

resources/jquery/jquery.byteLimit.js
tests/qunit/suites/resources/jquery/jquery.byteLimit.js

index 907ceb6..c1d26fc 100644 (file)
                        }
        
                        var len = $.byteLength( this.value );
+                       // Note that keypress returns a character code point, not a keycode.
+                       // However, this may not be super reliable depending on how keys come in...
+                       var charLen = $.byteLength( String.fromCharCode( e.which ) );
 
-                       // limit-3 as this doesn't count the character about to be inserted.
-                       if ( len > ( limit-3 ) ) {
+                       if ( ( len + charLen ) > limit ) {
                                e.preventDefault();
                        }
                });
index 902d813..bc69f9b 100644 (file)
@@ -151,5 +151,5 @@ byteLimitTest({
        sample: mbSample,
        useLimit: true,
        limit: 12,
-       expected: 10 // 10 x 1-byte char. The next 3-byte char exceeds limit of 12
+       expected: 12 // 10 x 1-byte char. The next 3-byte char exceeds limit of 12, but 2 more 1-byte chars come in after.
 });