(bug 28650) Refactor dynamic byte-based maxlength of edit summary into a jQuery plugi...
[lhc/web/wiklou.git] / resources / jquery / jquery.byteLimit.js
1 /**
2 * jQuery byteLimit
3 */
4 ( function( $ ) {
5
6 /**
7 * Enforces a byte limit to a textbox, so that UTF-8 entries are not arbitrarily truncated.
8 */
9 $.fn.byteLimit = function( limit ) {
10 return $(this).attr( 'maxLength', limit ).keypress( function( e ) {
11 // first check to see if this is actually a character key
12 // being pressed.
13 // Based on key-event info from http://unixpapa.com/js/key.html
14 // jQuery should also normalize e.which to be consistent cross-browser,
15 // however the same check is still needed regardless of jQuery.
16
17 // Note: At the moment, for some older opera versions (~< 10.5)
18 // some special keys won't be recognized (aka left arrow key).
19 // Backspace will be, so not big issue.
20
21 if ( e.which === 0 || e.charCode === 0 || e.which === 8 ||
22 e.ctrlKey || e.altKey || e.metaKey )
23 {
24 return true; //a special key (backspace, etc) so don't interfere.
25 }
26
27 // This basically figures out how many bytes a UTF-16 string (which is what js sees)
28 // will take in UTF-8 by replacing a 2 byte character with 2 *'s, etc, and counting that.
29 // Note, surrogate (\uD800-\uDFFF) characters are counted as 2 bytes, since there's two of them
30 // and the actual character takes 4 bytes in UTF-8 (2*2=4). Might not work perfectly in edge cases
31 // such as illegal sequences, but that should never happen.
32
33 var len = this.value.replace( /[\u0080-\u07FF\uD800-\uDFFF]/g, '**' ).replace( /[\u0800-\uD7FF\uE000-\uFFFF]/g, '***' ).length;
34 // limit-3 as this doesn't count character about to be inserted.
35 if ( len > ( limit-3 ) ) {
36 e.preventDefault();
37 }
38 });
39 };
40
41 } )( jQuery );