Javascript 如何防止在输入字段中输入无效字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8282266/
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 to prevent invalid characters from being typed into input fields
提问by Mike
Onkeydown
, I run the following JavaScript:
Onkeydown
,我运行以下 JavaScript:
function ThisOnKeyDown(el) {
if (el.title == 'textonly') {
!(/^[A-Za-z??-\s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-z??-\s]/ig, '') : null;
}
if (el.title == 'numbersonly') {
!(/^[0-9]*$/i).test(el.value) ? el.value = el.value.replace(/[^0-9]/ig, '') : null;
}
if (el.title == 'textandnumbers') {
!(/^[A-Za-z??0-9-\s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-z??0-9-\s]/ig, '') : null;
}
}
One of these three title attributes is given to various input fields on the page. The code works so far as invalid characters are correctly erased, but not until the next character is entered. I want to find a way to simply deny the invalid input in the first place. I appreciate your help!
这三个标题属性之一被赋予页面上的各种输入字段。只要无效字符被正确擦除,代码就可以工作,但直到输入下一个字符才有效。我想首先找到一种简单地拒绝无效输入的方法。我感谢您的帮助!
Edit: I create the events globally. Here's how I do that:
编辑:我在全球范围内创建事件。这是我如何做到的:
function Globalization() {
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
inputs[i].onfocus = createEventHandler(
ThisOnFocus, inputs[i]);
inputs[i].onblur = createEventHandler(
ThisOnBlur, inputs[i]);
inputs[i].onkeydown = createEventHandler(
ThisOnKeyDown, inputs[i]);
inputs[i].onkeyup = createEventHandler(
ThisOnKeyUp, inputs[i]);
}
}
Globalization()
is run body.onload
Globalization()
正在运行 body.onload
Therefore, a typical input field has HTML without function calls like this:
因此,典型的输入字段具有 HTML,没有像这样的函数调用:
<input id="AppFirstName" style="width: 150px;" type="text" maxlength="30" title="textonly"/>
回答by user1034772
To prevent it from being set in the first place, you can return false on the keydown event handler, thus preventing the event from propagating any further.
为了防止它首先被设置,您可以在 keydown 事件处理程序上返回 false,从而防止事件进一步传播。
I wrote the example below using jQuery, but you can use the same function when binding traditionally.
我使用 jQuery 编写了下面的示例,但是您可以在传统绑定时使用相同的函数。
Though it's important to validate on the server-side as well, client-side validation is important for the sake of user friendliness.
尽管在服务器端验证也很重要,但为了用户友好性,客户端验证很重要。
$("input.number-only").bind({
keydown: function(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
}
});
回答by Michael Adekunle Salami
The above code does it says- allows ONLY numbers. You can modify it by adding exception to say BACKSPACE for example like this
上面的代码确实说 - 只允许数字。您可以通过添加异常来修改它,例如像这样说 BACKSPACE
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function keyispressed(e){
var charValue= String.fromCharCode(e.keyCode);
if((isNaN(charValue)) && (e.which != 8 )){ // BSP KB code is 8
e.preventDefault();
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeydown="return keyispressed(event);"/>
</body>
</html>
回答by user2415200
$('.key-filter').keypress(function () {
if (event.key.replace(/[^\w\-.]/g,'')=='') event.preventDefault();
});
then add the key-filter class to your input if using jquery or
如果使用 jquery 或
<input type="text" onkeypress="if (event.key.replace(/[^\w\-.]/g,'')=='') event.preventDefault();" />
just put the charaters you want to allow inside the [] after the ^. this allows all letters numbers _ - and .
只需将您想要允许的字符放在 ^ 之后的 [] 中。这允许所有字母数字 _ - 和 .
回答by rui
i found this solution in: http://help.dottoro.com/ljlkwans.php
我在以下位置找到了这个解决方案:http: //help.dottoro.com/ljlkwans.php
works as intended.
按预期工作。
<script type="text/javascript">
function FilterInput (event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
isNumeric = (keyCode >= 48 /* KeyboardEvent.DOM_VK_0 */ && keyCode <= 57 /* KeyboardEvent.DOM_VK_9 */) ||
(keyCode >= 96 /* KeyboardEvent.DOM_VK_NUMPAD0 */ && keyCode <= 105 /* KeyboardEvent.DOM_VK_NUMPAD9 */);
modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
return !isNumeric || modifiers;
}
</script>
< body>
The following text field does not accept numeric input:
<input type="text" onkeydown="return FilterInput (event)" />< /body>
it allows text and !"#$%& but you can adjust it adding these to the validationto only allow numbers by removing the ! in the return
它允许文本和 !"#$%& 但你可以调整它,将这些添加到验证中,通过删除返回中的 ! 来只允许数字
回答by akta kalariya
Code is useful for preventing user from typing any other character except number.
代码可用于防止用户键入除数字以外的任何其他字符。
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function keyispressed(e){
var charval= String.fromCharCode(e.keyCode);
if(isNaN(charval)){
return false;
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeydown="return keyispressed(event);"/>
</body>
</html>
回答by Dustin Spengler
You could easily do this in a single html line.
您可以在单个 html 行中轻松完成此操作。
Like this to disallow spaces:
像这样禁止空格:
<input type="text" onkeypress="return event.charCode != 32">
Or this to only allow numbers:
或者这只允许数字:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
Just look up the unicodeof any numbers you want to allow or disallow.
只需查找您要允许或禁止的任何数字的unicode。
回答by austincheney
Run your code against the onkeyup event and not the onkeydown event. This way you can access the result of the very last keystroke where as the onkeyup event executes as a key is pressed without knowing its result.
针对 onkeyup 事件而不是 onkeydown 事件运行您的代码。通过这种方式,您可以访问最后一次击键的结果,当 onkeyup 事件在不知道其结果的情况下按下键时执行。