javascript 防止特殊字符输入到 html 文本字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3552301/
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
Preventing special character input to html text field
提问by JDC
I have an input text field that needs to be limited as to what characters can be typed in. As one form of defense against faulty input, I'm trying to not even let the user type in incorrect things. The input can be [a-zA-Z-._] characters and is limited to 32 characters.
我有一个输入文本字段,需要限制可以输入的字符。作为防止错误输入的一种形式,我试图甚至不让用户输入错误的内容。输入可以是 [a-zA-Z-._] 个字符,并且限制为 32 个字符。
<input id="aliasEntry" type="text" maxlength="32">
As you can see, I've already got the 32 character limit figured out, and the user is prevented from typing any more after the limit has been reached. But I'm having a problem with preventing the input of incorrect characters.
如您所见,我已经确定了 32 个字符的限制,并且在达到限制后用户将无法再输入任何内容。但是我在防止输入错误字符方面遇到了问题。
I've tried using jquery's .keypress() and .keydown() event catchers to do things similar to the following:
我试过使用 jquery 的 .keypress() 和 .keydown() 事件捕捉器来做类似于以下的事情:
$("#aliasEntry").keypress(function(e)
{
var code = e.which || e.keyCode;
// 65 - 90 for A-Z and 97 - 122 for a-z 95 for _ 45 for - 46 for .
if (!((code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code == 95 || code == 46 || code == 45))
{
var text = $("#aliasEntry").val();
text = text.substring(0,text.length);
$("#aliasEntry").val(text);
}
});
But The problem with this is that the browsers always insert the typed character into the text box AFTER the event has been handled, which makes the code useless because the character I'm trying to eliminate hasn't been entered yet. Is there a way to simply prevent the browser from inserting the character into the text box after the user types it?
但问题是浏览器总是在处理事件后将键入的字符插入文本框中,这使得代码无用,因为我试图消除的字符尚未输入。有没有办法简单地防止浏览器在用户键入字符后将其插入文本框中?
采纳答案by li.davidm
You're using jQuery, so see this:http://api.jquery.com/event.preventDefault/.
Just call e.preventDefault()if the character happens to be invalid, and this should prevent the default browser action from occurring, which in this case would be the insertion of a character.
您正在使用 jQuery,因此请参阅:http: //api.jquery.com/event.preventDefault/。只需e.preventDefault()在字符碰巧无效时调用,这应该可以防止默认浏览器操作发生,在这种情况下将是插入字符。
回答by Safa Hikmat
Use your input like this
像这样使用您的输入
<input maxlength="32" onKeyUp="chText()" onKeyDown="chText()" id="aliasEntry"/>
and make chText()function on javascript write in it
this code below
并chText()在javascript上编写函数在下面写下这段代码
function chText()
{
var str=document.getElementById("aliasEntry");
var regex=/[^a-z]/gi;
str.value=str.value.replace(regex ,"");
}
it will not allow any char to enter except a-zand A-Z
它不允许任何字符进入,除了a-z和A-Z

