5

テキストボックスへの特殊文字の貼り付けを無効にする方法は?

onkeypress イベント ハンドラを使用しています

function disableOtherChar(evt) {
    var charCode;
    charCode = (evt.which) ? evt.which : evt.keyCode;
    var ctrl;
    ctrl = (document.all) ? event.ctrlKey : evt.modifiers & Event.CONTROL_MASK;
    if ((charCode > 47 && charCode < 58) || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || charCode == 9 || charCode == 45 || (ctrl && charCode == 86) || ctrl && charCode == 67) {
        return true;
    } else {
        $(":text").live("cut copy paste", function (e) {
            e.preventDefault();
        });
        return false;
    }
}

ただし、貼り付け時に特殊文字をブロックせず、入力時にのみ、

4

4 に答える 4

13

入力があるとします

 <input id="textInput" name="textInput">

そして、コピーを検証するための次のスクリプトがあります。

$(function(){

   $( "#textInput" ).bind( 'paste',function()
   {
       setTimeout(function()
       { 
          //get the value of the input text
          var data= $( '#textInput' ).val() ;
          //replace the special characters to '' 
          var dataFull = data.replace(/[^\w\s]/gi, '');
          //set the new value of the input text without special characters
          $( '#textInput' ).val(dataFull);
       });

    });
});
于 2013-05-28T03:28:00.123 に答える
0

答えではなく、次に関するコメントです。

var ctrl;
ctrl = (document.all) ? event.ctrlKey:evt.modifiers & Event.CONTROL_MASK;

機能検出の使用方法を学んでください。オブジェクトの推論に基づく動作の推論は、少なくともある程度の時間は失敗する運命にあります。

また、キーコードは使用せず、実際の文字をテストしてください。たとえば、文字、数字、およびその他のいくつかを許可する場合:

function hasInvalidChars(s) {

  // allow letters, spaces, numbers only
  var validChars = /[\w\s\d]/gi;
  var x = s.replace(validChars, '');
  return !!x.length;
}

alert(hasInvalidChars('asdf1234 1234asd'));  // false
alert(hasInvalidChars('asdf1.234 1234asd')); // true

有効な文字のセットを必要なものに拡張します。

ああ、ワンライナーにしたい場合:

function hasInvalidChars(s) {
  return !!s.replace(/[\w\s\d]/gi, '').length;
}
于 2013-05-28T02:59:00.350 に答える