javascript 如何防止用户使用 jQuery 在文本框中输入特定字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13229224/
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-10-26 18:08:36  来源:igfitidea点击:

How do I prevent user from entering specific characters in a textbox using jQuery?

javascriptjqueryjquery-events

提问by Randel Ramirez

I have a regular expression that will be matched against the keypress of the user. I'm quite stuck with it.

我有一个正则表达式,它将与用户的按键匹配。我很坚持。

Here is my current code:

这是我当前的代码:

<script type="text/javascript">
    $('input.alpha[$id=tb1]').keydown(function (e) {
        //var k = e.which;
        //var g = e.KeyCode;
        var k = $(this).val();
        //var c = String.fromCharCode(e.which);
        if (k.value.match(/[^a-zA-Z0-9 ]/g)) {
            e.preventDefault();
        }
    });
</script>

The goal here is to prevent the user from typing characters that are inside the regex.

这里的目标是防止用户输入正则表达式中的字符。

采纳答案by Korikulum

Try using the fromCharCodemethod:

尝试使用fromCharCode方法:

$(document).ready(function () {
  $('#tb1').keydown(function (e) {

    var k = String.fromCharCode(e.which);

    if (k.match(/[^a-zA-Z0-9]/g))
      e.preventDefault();
  });
});

回答by T.J. Crowder

You use keypressrather than keydownand prevent the default action.

您使用keypress而不是keydown并阻止默认操作。

For example, this prevents typing a winto the text input:

例如,这可以防止w在文本输入中键入 a :

$("#target").keypress(function(e) {
  if (e.which === 119) { // 'w'
    e.preventDefault();
  }
});

Live Copy| Source

实时复制| 来源

Update: If it's applying the regex that's giving you trouble:

更新:如果它正在应用给您带来麻烦的正则表达式:

$("#target").keypress(function(e) {
  if (String.fromCharCode(e.which).match(/[^A-Za-z0-9 ]/)) {
    e.preventDefault();
  }
});

Live Copy| Source

实时复制| 来源