【问题标题】:How do I prevent user from entering specific characters in a textbox using jQuery?如何防止用户使用 jQuery 在文本框中输入特定字符?
【发布时间】:2020-01-27 06:38:44
【问题描述】:

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

这是我当前的代码:

<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>

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

【问题讨论】:

  • "这是 IE9 上的错误信息。": where ?
  • 为什么k.value,当k = $(this).val()?你检查过重复吗?我相信在SO上有很多类似的问题。请参阅thisthisthis 等等……
  • 我一直在调整代码,这就是为什么它有点乱。我想要做的是,如果用户在键盘上按下了一个字符并且它与正则表达式匹配,它将阻止默认。
  • @randelramirez1:我的回答有什么不清楚的地方,我可以为你澄清一下吗?
  • @randelramirez1 脚本的主要问题是,$(this).val() 是输入的值 之前 键被按下,这意味着你不检查最后按下的键..跨度>

标签: javascript jquery jquery-events


【解决方案1】:

尝试使用fromCharCode 方法:

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

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

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

【讨论】:

  • 这只有一个问题。它也会阻止退格键。
  • @MichaelS.Miller 如果您也想保留退格,只需将\x08 添加到正则表达式:/[^a-zA-Z0-9\x08]/g
【解决方案2】:

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

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

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

Live Copy | Source

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

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

Live Copy | Source

【讨论】:

    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多