Javascript限制文本输入字符

发布于 2024-10-30 07:42:58 字数 585 浏览 4 评论 0原文

我想将文本框的输入字符限制为 [a-z0-9_-]。但是,每当执行此操作时,退格键和箭头键等按钮就不起作用。我在这个网站和其他网站上发现了一些尝试,但它们要么不能在所有浏览器上正常工作,要么使用黑名单。例如,W3Schools 网站示例将号码列入黑名单。有没有一种方法可以使用白名单(上面的)并且仍然允许使用退格键、箭头、home、end 等键?或者我是否必须添加与我想要允许的按键匹配的所有按键代码?我做了类似的事情(为了简单起见,缩短了)。

编辑 - 添加代码

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

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 example black 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).

EDIT - Added code

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

浅黛梨妆こ 2024-11-06 07:42:58

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

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

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

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

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

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

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

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

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-]/;
悟红尘 2024-11-06 07:42:58

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

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

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.

琉璃繁缕 2024-11-06 07:42:58

是的,您可以限制字符的输入。例如,创建一个函数来检查正在发生的情况,如果一切正常则返回 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;
}

一旦有了该函数,将其挂接到您的输入中(这是使用 jQuery):

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

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

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;
}

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:

// 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):

$('#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;
}
超可爱的懒熊 2024-11-06 07:42:58

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

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

You can press any key you like, as long as you keep the value from 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,'');
}
老子叫无熙 2024-11-06 07:42:58

将此代码添加到 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));

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

Add this code to onkeypress event.

    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;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文