javascript 如何防止用户使用 jQuery 在文本框中输入特定字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13229224/
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
How do I prevent user from entering specific characters in a textbox using jQuery?
提问by Randel Ramirez
I have a regular expression that will be matched against the keypress of the user. I'm quite stuck with it.
我有一个正则表达式,它将与用户的按键匹配。我很坚持。
Here is my current code:
这是我当前的代码:
<script type="text/javascript">
$('input.alpha[$id=tb1]').keydown(function (e) {
//var k = e.which;
//var g = e.KeyCode;
var k = $(this).val();
//var c = String.fromCharCode(e.which);
if (k.value.match(/[^a-zA-Z0-9 ]/g)) {
e.preventDefault();
}
});
</script>
The goal here is to prevent the user from typing characters that are inside the regex.
这里的目标是防止用户输入正则表达式中的字符。
采纳答案by Korikulum
Try using the fromCharCodemethod:
尝试使用fromCharCode方法:
$(document).ready(function () {
$('#tb1').keydown(function (e) {
var k = String.fromCharCode(e.which);
if (k.match(/[^a-zA-Z0-9]/g))
e.preventDefault();
});
});
回答by T.J. Crowder
You use keypress
rather than keydown
and prevent the default action.
您使用keypress
而不是keydown
并阻止默认操作。
For example, this prevents typing a w
into the text input:
例如,这可以防止w
在文本输入中键入 a :
$("#target").keypress(function(e) {
if (e.which === 119) { // 'w'
e.preventDefault();
}
});
Update: If it's applying the regex that's giving you trouble:
更新:如果它正在应用给您带来麻烦的正则表达式:
$("#target").keypress(function(e) {
if (String.fromCharCode(e.which).match(/[^A-Za-z0-9 ]/)) {
e.preventDefault();
}
});