jQuery 如何禁用特殊字符粘贴到文本框中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16782734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:46:13  来源:igfitidea点击:

How to disable special characters from paste in a textbox

javascriptjqueryhtml

提问by JeAr

How to disable special characters from paste in a textbox?

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

Im using a onkeypress event handler

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

But it doesnt block special characters when pasting, only in entering,

但是在粘贴的时候不会屏蔽特殊字符,只有在输入的时候,

回答by Cristian Chaparro A.

suppose that you have a Input

假设你有一个输入

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

and you have the following script to validate the copy:

并且您有以下脚本来验证副本:

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

    });
});

回答by RobG

Not an answer, just a comment regarding:

不是答案,只是关于以下内容的评论:

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

Please learn to use feature detection, inferring behaviour based on object inference is doomed to fail at least some of the time.

请学会使用特征检测,基于对象推断的推断行为至少在某些时候注定会失败。

Also, don't use the key code, test the actual characters. E.g if you just want to allow letters, numbers and few others:

另外,不要使用密钥代码,测试实际字符。例如,如果您只想允许字母、数字和其他几个:

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

Expand the set of valid characters to whatever you want.

将有效字符集扩展为您想要的任何内容。

Oh, if you want it as a one–liner:

哦,如果你想把它作为单线:

function hasInvalidChars(s) {
  return !!s.replace(/[\w\s\d]/gi, '').length;
}

回答by Philip D.

You could use a 3rd party plugin like jquery.alphanum, it works for paste (ctrl+v) too. The code looks like this :

您可以使用像jquery.alphanum这样的 3rd 方插件,它也适用于粘贴(ctrl+v)。代码如下所示:

$("input").alphanum();

$("input").alphanum();

Or you could use it in a more spceficied way like this :

或者你可以像这样以更规范的方式使用它:

$("#elemet").alphanum({
    allow      : "asd",
    disallow   : "!@#",
    allowUpper : false
});

The above code you need to add it into your JQuery declaration.

您需要将上面的代码添加到您的 JQuery 声明中。

I mention the fact that you can also modify the blacklistarray from the script jquery.alphanum.json line 124. You will find a function name getBlacklistAscii, in that you modify var blacklist = ...to what suits you.

我提到您还可以在第 124 行的脚本中修改黑名单数组jquery.alphanum.js。您将找到一个函数名称getBlacklistAscii,您可以修改var blacklist = ...为适合您的内容。

回答by Tk421

I have changed a bit the script provided by Christian.

我对 Christian 提供的脚本进行了一些更改。

This version replaces everything that is not between spaces(ASCII DEC 32) to tilde(ASCII DEC 126) and whitespace characters. Meaning all characters that are not-visible should be removed.

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

If you add the class api_clean_charactersin a Jquery environment this should work out of the box.

如果您在 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);
        });

    });
});