You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript正则限制输入仅字母数字时无法删除首个输入内容问题

问题根因

你使用的校验正则/^[^\W_]+$/i中的+量词要求输入内容至少包含1个字符,当你删除所有内容得到空字符串时,正则校验失败,代码会自动回滚到上一次有效的旧值(也就是你输入的第一个字符),因此无法彻底删除内容。

修复方案

只需要修改校验规则,允许空字符串通过校验即可:将正则中的+替换为*,*表示匹配0个或多个符合规则的字符,空字符串也会被判定为合法值。

修改后的完整代码如下:

function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
       textbox.addEventListener(event, function() {
              if (inputFilter(this.value)) {
                this.oldValue = this.value;
                this.oldSelectionStart = this.selectionStart;
                this.oldSelectionEnd = this.selectionEnd;
                console.log("If 1");
              } else if (this.hasOwnProperty("oldValue")) {
                this.value = this.oldValue;
                this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                console.log("if 2");
              } else {
                  console.log("if 3");
                this.value = "";
              }
            });
          });
    }
    
setInputFilter(document.getElementById("frm_nuevo_proveedor:j_idt35"), function(value) {
    // 将+替换为*,允许空值通过校验
    return /^[^\W_]*$/i.test(value); 
});

内容的提问来源于stack exchange,提问作者Mario Ochoa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 10:06:02