jquery - 验证按键上的字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2812585/
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
jquery - validate characters on keypress?
提问by TwixxyKit
I have a form text field that I want to allow only numbers and letters in. (i.e., no #$!, etc...) Is there a way to throw up an error and prevent the keypress from actually outputting anything if the user tries to use any character other than numbers and letters? I've been trying to find a plugin, but haven't really found anything that does this...
我有一个表单文本字段,我只想允许输入数字和字母。(即,没有 #$!等...)有没有办法抛出错误并防止按键实际上输出任何内容,如果用户尝试使用数字和字母以外的任何字符?我一直在试图找到一个插件,但还没有真正找到任何可以做到这一点的东西......
回答by user113716
$('input').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.'); return ''; } ) );
});
EDIT:
编辑:
There are some other good answers here that will prevent the input from taking place.
这里还有一些其他好的答案可以防止输入发生。
I've updated mine since you also wanted to show an error. The replace can take a function instead of a string. The function runs and returns a replacement value. I've added an alert
to show the error.
我已经更新了我的,因为你也想显示一个错误。替换可以采用函数而不是字符串。该函数运行并返回一个替换值。我添加了一个alert
来显示错误。
回答by Juriy
Well the patrick's answer removes character if it is wrong, to actually preventcharacter from being inserted into the field use
好吧,帕特里克的回答会删除错误的字符,以实际防止字符被插入到字段中使用
$("#field").keypress(function(e) {
// Check if the value of the input is valid
if (!valid)
e.preventDefault();
});
This way the letter will not come to textarea
这样信件就不会出现在 textarea 中
回答by ThiefMaster
$('#yourfield').keydown(function(e) {
// Check e.keyCode and return false if you want to block the entered character.
});
回答by BraveNewMath
I found that combining validation on keypress and keyup gives the best results. Key up is a must if you want to handle copy pasted text. It is also a catch all in case of cross browser issues which allow non numeric values into your textbox.
我发现结合对 keypress 和 keyup 的验证可以得到最好的结果。如果您想处理复制粘贴的文本,则必须使用键。如果出现跨浏览器问题,允许非数值进入您的文本框,这也是一个问题。
$("#ZipCode").keypress(function (event) {
var key = event.which || event.keyCode; //use event.which if it's truthy, and default to keyCode otherwise
// Allow: backspace, delete, tab, and enter
var controlKeys = [8, 9, 13];
//for mozilla these are arrow keys
if ($.browser.mozilla) controlKeys = controlKeys.concat([37, 38, 39, 40]);
// Ctrl+ anything or one of the conttrolKeys is valid
var isControlKey = event.ctrlKey || controlKeys.join(",").match(new RegExp(key));
if (isControlKey) {return;}
// stop current key press if it's not a number
if (!(48 <= key && key <= 57)) {
event.preventDefault();
return;
}
});
$('#ZipCode').keyup(function () {
//to allow decimals,use/[^0-9\.]/g
var regex = new RegExp(/[^0-9]/g);
var containsNonNumeric = this.value.match(regex);
if (containsNonNumeric)
this.value = this.value.replace(regex, '');
});
回答by P.Akarapong
$(document).ready(function() {
$('.ipFilter').keydown((e) => {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true) ||
e.keyCode === 67 && (e.ctrlKey === true || e.metaKey === true) ||
e.keyCode === 86 && (e.ctrlKey === true || e.metaKey === true) ||
e.keyCode === 82 && (e.ctrlKey === true || e.metaKey === true)) ||
(e.keyCode >= 35 && e.keyCode <= 40 )) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
回答by Kelsey
You could try this extension:
你可以试试这个扩展:
jQuery.fn.ForceAlphaNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, letters, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 65 && key <= 90) ||
(key >= 96 && key <= 105));
})
})
};
Useage:
用途:
$("#yourInput").ForceAlphaNumericOnly();
回答by Dale Rodgie
The above jquery extension (ForceAlphaNumericOnly) is good but still allows the following characters through !@#$%^&*()
上面的 jquery 扩展 (ForceAlphaNumericOnly) 很好,但仍然允许以下字符通过 !@#$%^&*()
On my Mac, when you press the shiftkey (keycode 16
) and then 1, it enters !
but the keycode is 49
, the keycode for 1
.
在我的 Mac 上,当您按下shift键(键码16
)然后按下 时1,它会进入,!
但键码是49
,是1
.