0

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

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

4

3 回答 3

5

​您只需检查 keyCodekeydownpreventDefault()在匹配时运行:

$('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/

于 2012-08-16T11:26:37.073 回答
0

我做了类似的事情,但使用的是 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;
                });
            });
        }
于 2012-08-16T11:34:00.320 回答
-1

我建议对退格键删除键等修饰键使用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/(尝试输入点.或分号;

于 2012-08-16T11:46:36.860 回答