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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11986079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:58:05  来源:igfitidea点击:

How to allow only defined characters as input using jQuery?

javascriptjquery

提问by net user

How do i allow special characters such as hyphen,comma,slash,space key,backspace key,delete key along with alphanumeric values and restrict the rest in jQuery?

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

As this criteria(allowed characters/input values) varies from field to field, i would like to make it as a utility method which accepts input field id and allowed characters as parameters. for example: limitCharacters(textid, pattern)

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

回答by David Hellsing

?You can just check the keyCode on keydownand run preventDefault()if match:

?您可以只检查 keyCodekeydownpreventDefault()在匹配时运行:

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

http://jsfiddle.net/GVb6L/

http://jsfiddle.net/GVb6L/

If you need to restrict to certain chars AND keyCodes + make it into a jQuery plugin, try something like:

如果您需要限制某些字符和 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/

http://jsfiddle.net/DHCUg/

回答by Undefined

I did something like this but in jQuery plugin format. This example will only allow numbers and full stops.

我做了这样的事情,但在 jQuery 插件格式。这个例子将只允许数字和句号。

You can call this by writing:

你可以这样写:

$("input").forceNumeric();

And the plugin:

和插件:

            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;
                });
            });
        }

回答by elclanrs

I would suggest using Davidsolution for modifier keys like backspaceand deleteand this code below for characters:

我建议将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));
  }
});

Also, I've experienced some problems with keydownso I'd do it on keyup.

另外,我遇​​到了一些问题,keydown所以我会在keyup.

Demo:http://jsfiddle.net/elclanrs/QjVGV/(try typing a dot .or semicolon ;)

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