Jquery允许字母数字字符和非文本键按下 [英] Jquery to allow alphanumeric characters and non-text key presses

查看:108
本文介绍了Jquery允许字母数字字符和非文本键按下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,用户应该只输入字母数字字符,并且应该允许非空格键按下,如退格键,箭头键等。此外,它也适用于所有主流浏览器(如Mozilla Firefox)。

I have one text box in which, user should enter only alphanumeric characters and non-text key presses should be allowed like backspace, arrow keys, etc . Also, it should also work on all major browsers (like Mozilla Firefox).

我尝试了几个例子,只允许我输入字母数字字符,但退格不起作用以下是Mozilla Firefox中的示例。

I have tried few examples which allowed to me enter only alphanumeric characters but backspace don't work with this below example in Mozilla Firefox.

$('input').bind('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
});


推荐答案

您可以添加 [\\ \\ b] 匹配并允许退格。

You can add [\b] to match and allow backspace.

代码:

var regex = new RegExp("^[a-zA-Z0-9\b]+$");

演示: http://jsfiddle.net/M3bvN/

而不是扩展你的正则表达式,你可以检查按下的键是否在允许键列表中(箭头,home,del,canc),如果是,则跳过验证。

Instead of extend your regex you can check if the pressed key is in a list of allowed keys (arrows, home, del, canc) and if so skip the validation.

这不是阻止用户复制/粘贴不允许的字符。所以也要在 blur 事件中执行验证控件(并且始终在服务器端)。

This not prevent the user to copy/paste not allowed characters. so perform the validation control in the blur event too (and always on server side).

代码:

var keyCode = event.keyCode || event.which
// Don't validate the input if below arrow, delete and backspace keys were pressed 
if (keyCode == 8 || (keyCode >= 35 && keyCode <= 40)) { // Left / Up / Right / Down Arrow, Backspace, Delete keys
    return;
}

演示: http://jsfiddle.net/M3bvN/3/

这篇关于Jquery允许字母数字字符和非文本键按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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