我如何使用 jquery 阻止或限制输入字段中的特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/895659/
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 block or restrict special characters from input fields with jquery?
提问by Nerd Stalker
How do I block special characters from being typed into an input field with jquery?
如何使用 jquery 阻止将特殊字符输入到输入字段中?
回答by Dale
A simple example using a regular expression which you could change to allow/disallow whatever you like.
一个使用正则表达式的简单示例,您可以将其更改为允许/禁止您喜欢的任何内容。
$('input').on('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;
}
});
回答by rexmac
I was looking for an answer that restricted input to only alphanumeric characters, but still allowed for the use of control characters (e.g., backspace, delete, tab) and copy+paste. None of the provided answers that I tried satisfied all of these requirements, so I came up with the following using the input
event.
我正在寻找一个答案,该答案将输入限制为仅字母数字字符,但仍允许使用控制字符(例如退格、删除、制表符)和复制+粘贴。我尝试提供的答案都没有满足所有这些要求,因此我使用该input
事件提出了以下内容。
$('input').on('input', function() {
$(this).val($(this).val().replace(/[^a-z0-9]/gi, ''));
});
Edit:
As rinogopointed out in the comments, the above code snippet forces the cursor to the end of the input when typing in the middle of the input text. I believe the code snippet below solves this problem.
编辑:
正如rinogo在评论中指出的那样,在输入文本的中间键入时,上面的代码片段会强制光标移动到输入的末尾。我相信下面的代码片段可以解决这个问题。
$('input').on('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
回答by KevSheedy
Short answer:prevent the 'keypress' event:
简短回答:防止“按键”事件:
$("input").keypress(function(e){
var charCode = !e.charCode ? e.which : e.charCode;
if(/* Test for special character */ )
e.preventDefault();
})
Long answer:Use a plugin like jquery.alphanum
长答案:使用像jquery.alphanum这样的插件
There are several things to consider when picking a solution:
选择解决方案时需要考虑以下几点:
- Pasted text
- Control characters like backspace or F5 may be prevented by the above code.
- é, í, ? etc
- Arabic or Chinese...
- Cross Browser compatibility
- 粘贴的文本
- 上面的代码可以防止像退格或 F5 这样的控制字符。
- é, í, ? 等等
- 阿拉伯语或中文...
- 跨浏览器兼容性
I think this area is complex enough to warrant using a 3rd party plugin. I tried out several of the available plugins but found some problems with each of them so I went ahead and wrote jquery.alphanum. The code looks like this:
我认为这个领域足够复杂,可以保证使用 3rd 方插件。我尝试了几个可用的插件,但发现每个插件都存在一些问题,所以我继续编写jquery.alphanum。代码如下所示:
$("input").alphanum();
Or for more fine-grained control, add some settings:
或者为了更细粒度的控制,添加一些设置:
$("#username").alphanum({
allow : "$£",
disallow : "xyz",
allowUpper : false
});
Hope it helps.
希望能帮助到你。
回答by keepitreal
Use HTML5's pattern input attribute!
使用 HTML5 的模式输入属性!
<input type="text" pattern="^[a-zA-Z0-9]+$" />
回答by chandler
Your textbox:
您的文本框:
<input type="text" id="name">
Your javascript:
你的javascript:
$("#name").keypress(function(event) {
var character = String.fromCharCode(event.keyCode);
return isValid(character);
});
function isValid(str) {
return !/[~`!@#$%\^&*()+=\-\[\]\';,/{}|\":<>\?]/g.test(str);
}
回答by James Mart
Use regex to allow/disallow anything. Also, for a slightly more robust version than the accepted answer, allowing characters that don't have a key value associated with them (backspace, tab, arrow keys, delete, etc.) can be done by first passing through the keypress event and check the key based on keycode instead of value.
使用正则表达式允许/禁止任何事情。此外,对于比接受的答案更强大的版本,可以通过首先通过 keypress 事件和根据键码而不是值检查键。
$('#input').bind('keydown', function (event) {
switch (event.keyCode) {
case 8: // Backspace
case 9: // Tab
case 13: // Enter
case 37: // Left
case 38: // Up
case 39: // Right
case 40: // Down
break;
default:
var regex = new RegExp("^[a-zA-Z0-9.,/ $@()]+$");
var key = event.key;
if (!regex.test(key)) {
event.preventDefault();
return false;
}
break;
}
});
回答by RSolberg
Take a look at the jQuery alphanumeric plugin. https://github.com/KevinSheedy/jquery.alphanum
看看 jQuery 字母数字插件。https://github.com/KevinSheedy/jquery.alphanum
//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});
回答by Pratik 1020
Write some javascript code on onkeypress event of textbox. as per requirement allow and restrict character in your textbox
在文本框的 onkeypress 事件上编写一些 javascript 代码。根据要求允许和限制文本框中的字符
function isNumberKeyWithStar(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 42)
return false;
return true;
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function isNumberKeyForAmount(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
return true;
}
回答by Pablo Padron
I use this code modifying others that I saw. Only grand to the user write if the key pressed or pasted text pass the pattern test (match) (this example is a text input that only allows 8 digits)
我使用此代码修改我看到的其他代码。如果按键按下或粘贴的文本通过模式测试(匹配),则仅向用户写入(此示例是仅允许 8 位数字的文本输入)
$("input").on("keypress paste", function(e){
var c = this.selectionStart, v = $(this).val();
if (e.type == "keypress")
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode)
else
var key = e.originalEvent.clipboardData.getData('Text')
var val = v.substr(0, c) + key + v.substr(c, v.length)
if (!val.match(/\d{0,8}/) || val.match(/\d{0,8}/).toString() != val) {
e.preventDefault()
return false
}
})
回答by Ranjith Rana
$(function(){
$('input').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
});
});