禁用输入字段中的符号和非字母

Disable symbols and non-letters in input field

本文关键字:符号 输入 字段      更新时间:2023-09-26

我想禁用所有与以下内容无关的符号输入:字母或数字或空格或&符号或句号

。ALLOWED:允许A-Z, A-Z, 0-9, &, .和空格。

不允许:每一个其他字符,例如!@ # $ % ^ * () - + = [];; ' " <>,/?| = ' ~ etc.

<input id="ItemName" type="text" />

您可以注册一个按键事件处理程序,如果您不"喜欢"新的输入,则返回false:

$('#ItemName').keypress(function (e) {
    var txt = String.fromCharCode(e.which);
    if (!txt.match(/[A-Za-z0-9&. ]/)) {
        return false;
    }
});

JSFiddle: http://jsfiddle.net/cgx1yqyf/

注意这个解决方案需要JQuery

正确的方法是使用"input"事件。document.addEventListener('input', script);https://developer.mozilla.org/en-US/docs/Web/Events/input

Question is old, but it's never too late to answer
$(document).ready(function() {
  //prevent paste
  var usern_paste = document.getElementById('yourid');
  usern_paste.onpaste = e => e.preventDefault();
  //prevent copy
  var usern_drop = document.getElementById('yourid');
  usern_drop.ondrop = e => e.preventDefault();
$('#yourid').keypress(function (e) {
  var regex = new RegExp("^[a-zA-Z0-9's]");
  var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
  if (regex.test(str)) {
      return true;
  }
  e.preventDefault();
  return false;
});
});

是的,是的,我知道。这个问题很老了。但我还是想试试(不使用jQuery)

<input type="text" placeholder="Try to put a non-alphabetical character here! (you can put a number and a space too)" id="nochars" />

JS

const input = document.getElementById("nochars"); // gets the element (the input) by it's id
input.addEventListener("input", (event) =>  {
  const char = String.fromCharCode(event.keyCode)); // changes the keycode from a int to a string
  if (!(/[a-zA-Z0-9's'.$]/.test(char))) {
    event.preventDefault(); // prevents the default (which is adding the character to the value)
  }
});

同时,检查EventTarget.addEventListener做什么。('s为空格)