如何使用jQuery仅允许定义的字符作为输入? [英] How to allow only defined characters as input using jQuery?

查看:72
本文介绍了如何使用jQuery仅允许定义的字符作为输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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)

推荐答案

你可以检查<$ c $上的keyCode c> keydown 并运行 preventDefault()如果匹配:

​You can just check the keyCode on keydown and run preventDefault() if match:

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

http://jsfiddle.net/GVb6L/

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

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

$.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仅允许定义的字符作为输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆