javascript javascript限制文本输入字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5534346/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:32:17  来源:igfitidea点击:

javascript limit text input characters

javascriptjavascript-eventswhitelistonkeypress

提问by Timothy Ruhle

I am wanting to restrict the input characters for a text box to [a-z0-9_-]. However whenever if do this buttons like backspace and the arrow keys don't work. I have found some attempts on this website and others but either they don't work properly on all browsers or they use a black list. For example the W3Schools website exampleblack lists numbers. Is there a way to use white list (the one above) and still allow keys like backspace, arrows, home, end etc? Or do i have to add everyone of the key codes that match the keys i want to allow? I do something like this (this is shortened for simplicity).

我想将文本框的输入字符限制为 [a-z0-9_-]。但是,无论何时执行此按钮,例如退格键和箭头键都不起作用。我在本网站和其他网站上找到了一些尝试,但要么无法在所有浏览器上正常工作,要么使用黑名单。例如W3Schools 网站示例黑名单数字。有没有办法使用白名单(上面的那个)并仍然允许退格、箭头、主页、结束等键?或者我是否必须添加与我想要允许的密钥匹配的所有密钥代码?我做这样的事情(为了简单起见缩短了)。

EDIT- Added code

编辑- 添加代码

 <input type="text" onkeypress="return checkInput();">
    function checkInput(){
        return /[a-z0-9_-]/gi.test(String.fromCharCode(window.event.keyCode));
    }

Thanks

谢谢

回答by awm

Just change the regex in the example to something like this:

只需将示例中的正则表达式更改为如下所示:

numcheck = /[^a-z0-9_-]/;

Or better yet, avoid the double negative with:

或者更好的是,避免双重否定:

numcheck = /[a-z0-9_-]/;
return numcheck.test(keychar);

Then you can look up the keycodes of backspace, etc. and check for them too:

然后您可以查找退格键等的键码并检查它们:

if (keychar === 8) return true;
...

Or even put them in your regex:

或者甚至将它们放在您的正则表达式中:

numcheck = /[a-z0-9_\x08-]/;

回答by KP Taylor

You haven't provided any code samples, so it's hard to be specific in a response, but as a general strategy, try this: instead of trying to whitelist characters that can be input while they are being typed in, validate the contents of the text box after every key stroke to make sure that it still contains valid characters. If it doesn't, remove the last character entered.

您尚未提供任何代码示例,因此很难在响应中具体说明,但作为一般策略,请尝试以下操作:不要尝试将可以在输入时输入的字符列入白名单,而是验证每次击键后的文本框,以确保它仍然包含有效字符。如果不是,请删除输入的最后一个字符。

This approach will allow special keys like backspace, etc., while at the same time achieve what it sounds like you are really after: a valid value in the text box.

这种方法将允许使用退格键等特殊键,同时实现您真正想要的:文本框中的有效值。

回答by Justin808

Yes you can limit the input of characters. For example create a function that checks what is going on, return true if everything is OK and false if not:

是的,您可以限制字符的输入。例如,创建一个检查正在发生的事情的函数,如果一切正常则返回 true,否则返回 false:

// return true for 1234567890A-Za-z - _
function InputCheck(e) {
    if ((e.shiftKey && e.keyCode == 45) || e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        if (e.which == 45 || e.which == 95 || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122))
            return true;
        return false;
    }
    return true;
}

once you have the function, hook it into you input (this is with jQuery):

一旦你有了这个函数,把它挂到你的输入中(这是用 jQuery):

$('#InputID').keypress(InputCheck);

You can make as complicated a check as you want, for example this will allow for USD money values:

您可以根据需要进行尽可能复杂的检查,例如这将允许美元货币价值:

function InputCheck(e) {
    if ((e.shiftKey && e.keyCode == 45) || e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46 && e.which != 36) {
        return false;
    }
    // . = 46
    // $ = 36
    var text = $(this).val();

    // Dollar sign first char only
    if (e.which == 36 && text.length != 0) {
        return false;
    }

    // Only one decimal point
    if (e.which == 46 && text.indexOf('.') != -1) {
        return false;
    }

    // Only 2 numbers after decimal
    if (text.indexOf('.') != -1 && (text.length - text.indexOf('.')) > 2) {
        return false;
    }

    return true;
}

回答by kennebec

You can press any key you like, as long as you keep the valuefrom including anything not in the white-list.

您可以按您喜欢的任何键,只要您不让该包含任何不在白名单中的内容。

inputelement.onkeyup=function(e){
  e=e || window.event;
  var who=e.target || e.srcElement;
  who.value= who.value.replace(/[^\w-]+/g,'');
}

回答by Pradeepta

Add this code to onkeypress event.

将此代码添加到 onkeypress 事件。

    var code;
    document.all ? code = e.keyCode : code = e.which;
    return ((code > 64 && code < 91) || (code > 96 && code < 123) || code == 8 || code == 32 || (code >= 48 && code <= 57));

For browser compatibility, You can add var k = e.keyCode == 0 ? e.charCode : e.keyCode;

为了浏览器兼容性,您可以添加 var k = e.keyCode == 0 ? e.charCode : e.keyCode;