如何禁止在文本框中粘贴特殊字符

How to disable special characters from paste in a textbox

本文关键字:特殊字符 文本 何禁止 禁止      更新时间:2023-09-26

如何禁用在文本框中粘贴特殊字符?

我使用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;
    }
}

但粘贴时不屏蔽特殊字符,只在输入

时屏蔽

假设您有一个输入

 <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);
       });
    });
});

您可以使用第三方插件,如jquery。alpha,它也适用于粘贴(ctrl+v)。代码看起来像这样:

$("input").alphanum();

或者你可以用更具体的方式使用它,像这样:

<>前$ (" # elemet ") .alphanum ({允许:"asd",不允许:"!@ #",allowUpper: false});之前你需要将上面的代码添加到你的JQuery声明中。

我提到了这样一个事实,即您也可以在第124行jquery.alphanum.js脚本中修改blacklist数组。您将找到一个函数名getBlacklistAscii,在此您修改var blacklist = ...以适合您。

不是答案,只是关于

的评论:
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;
}

我对Christian提供的脚本做了一些修改。

此版本将不在空格 (ASCII DEC 32)到波浪 (ASCII DEC 126)和空白字符之间的所有内容替换。这意味着所有不可见的字符都应该被删除。

如果在Jquery环境中添加类api_clean_characters,则应该开箱即用。

<textarea class="api_clean_characters"></textarea>

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