如何使用jQuery仅允许定义的字符作为输入?

如何允许特殊字符,如连字符,逗号,斜杠,空格键,退格键,删除键以及字母数字值,并限制jQuery中的其余部分?

由于此标准(允许的字符/输入值)因字段而异,我想将其作为一种实用方法,它接受输入字段id和允许的字符作为参数。 例如:limitCharacters(textid,pattern)

您可以在keydown上检查keyCode,如果匹配则运行preventDefault()

 $('input').keydown(function(e) { if (e.which == 8) { // 8 is backspace e.preventDefault(); } });​ 

http://jsfiddle.net/GVb6L/

如果你需要限制某些字符和keyCodes +使它成为一个jQuery插件,尝试类似于:

 $.fn.restrict = function( chars ) { return this.keydown(function(e) { var found = false, i = -1; while(chars[++i] && !found) { found = chars[i] == String.fromCharCode(e.which).toLowerCase() || chars[i] == e.which; } found || e.preventDefault(); }); }; $('input').restrict(['a',8,'b']);​ 

http://jsfiddle.net/DHCUg/

我用jQuery插件格式做了类似的事情。 此示例仅允许数字和句号。

你可以这样写:

 $("input").forceNumeric(); 

和插件:

  jQuery.fn.forceNumeric = function () { return this.each(function () { $(this).keydown(function (e) { var key = e.which || e.keyCode; if (!e.shiftKey && !e.altKey && !e.ctrlKey && // numbers key >= 48 && key <= 57 || // Numeric keypad key >= 96 && key <= 105 || // comma, period and minus, . on keypad key == 190 || key == 188 || key == 109 || key == 110 || // Backspace and Tab and Enter key == 8 || key == 9 || key == 13 || // Home and End key == 35 || key == 36 || // left and right arrows key == 37 || key == 39 || // Del and Ins key == 46 || key == 45) return true; return false; }); }); } 

我建议使用David解决方案来修改键,例如退格删除 ,以下代码用于字符:

 var chars = /[,\/\w]/i; // all valid characters $('input').keyup(function(e) { var value = this.value; var char = value[value.length-1]; if (!chars.test(char)) { $(this).val(value.substring(0, value.length-1)); } }); 

另外,我在keydown遇到了一些问题所以我会在keyup上做到这一点。

演示: http //jsfiddle.net/elclanrs/QjVGV/ (尝试输入一个点.或分号;