问题描述
我想将文本框的输入字符限制为[a-z0-9_-]。但是,无论何时此按钮如退格键和箭头键都不起作用。我在本网站和其他网站上发现了一些尝试,但要么它们在所有浏览器上都无法正常工作,要么使用黑名单。例如,黑名单列出数字。有没有办法使用白名单(上面的那个),仍然允许像退格,箭头,家庭,结束等键?或者我是否必须添加与我想要允许的键匹配的每个键码?我这样做(为简单起见,这是缩短的。)
I am wanting to restrict the input characters for a text box to [a-z0-9_-]. However whenever if do this buttons like backspace and the arrow keys don't work. I have found some attempts on this website and others but either they don't work properly on all browsers or they use a black list. For example the W3Schools website example black lists numbers. Is there a way to use white list (the one above) and still allow keys like backspace, arrows, home, end etc? Or do i have to add everyone of the key codes that match the keys i want to allow? I do something like this (this is shortened for simplicity).
编辑 - 添加代码
<input type="text" onkeypress="return checkInput();">
function checkInput(){
return /[a-z0-9_-]/gi.test(String.fromCharCode(window.event.keyCode));
}
谢谢
推荐答案
只需将示例中的正则表达式更改为以下内容:
Just change the regex in the example to something like this:
numcheck = /[^a-z0-9_-]/;
或者更好的是,避免双重否定:
Or better yet, avoid the double negative with:
numcheck = /[a-z0-9_-]/;
return numcheck.test(keychar);
然后你可以查找退格键等的密码,并检查它们:
Then you can look up the keycodes of backspace, etc. and check for them too:
if (keychar === 8) return true;
...
甚至将它们放入你的正则表达式中:
Or even put them in your regex:
numcheck = /[a-z0-9_\x08-]/;
这篇关于javascript限制文本输入字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!