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

How to allow only defined characters as input using jQuery?

本文关键字:字符 输入 定义 jQuery 何使用 许定义      更新时间:2023-09-26

如何允许特殊字符,如连字符,逗号,斜杠,空格键,退格键,删除键以及字母数字值,并在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/

如果您需要限制为某些字符和键码 + 将其放入 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/(尝试键入点.或分号;