From 08ac8fa7f3d067a5c1cdef93c4e2c8287e5d1436 Mon Sep 17 00:00:00 2001 From: Brion Vibber Date: Mon, 11 Jul 2011 17:53:52 +0000 Subject: [PATCH] * (bug 29804) Fix byte-length-limited fields to check the length of to-be-added char instead of hardcoding a possible length of 3. 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 | 6 ++++-- tests/qunit/suites/resources/jquery/jquery.byteLimit.js | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/resources/jquery/jquery.byteLimit.js b/resources/jquery/jquery.byteLimit.js index 907ceb6c37..c1d26fc48d 100644 --- a/resources/jquery/jquery.byteLimit.js +++ b/resources/jquery/jquery.byteLimit.js @@ -43,9 +43,11 @@ } 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(); } }); diff --git a/tests/qunit/suites/resources/jquery/jquery.byteLimit.js b/tests/qunit/suites/resources/jquery/jquery.byteLimit.js index 902d8135bc..bc69f9bbf0 100644 --- a/tests/qunit/suites/resources/jquery/jquery.byteLimit.js +++ b/tests/qunit/suites/resources/jquery/jquery.byteLimit.js @@ -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. }); -- 2.20.1