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

如何修复带正则校验的JS数字输入函数清空整个字符串的问题

问题解决方法

问题原因

你原有代码的核心问题是使用了全匹配替换逻辑:只要当前输入的完整字符串不符合正则规则,就会将整个输入框内容替换为空,自然会清空已经输入的合法内容。

修复方案

我们采用合法值缓存回滚的逻辑实现需求:提前缓存每次校验通过的合法内容,新输入如果不符合规则,直接将输入框内容回滚为上一次的合法值即可,不会修改原有合法内容。

修改后代码

JavaScript 代码

// 初始化所有校验输入框的合法值缓存
$('.decimal').data('lastValidValue', '');

function restrictNumber(e) {
  const currentValue = this.value;
  // 规则1:仅允许输入数字和小数点
  if (!/^[0-9.]*$/.test(currentValue)) {
    this.value = $(this).data('lastValidValue');
    return;
  }
  // 规则2:最多1个小数点
  const dotAmount = (currentValue.match(/\./g) || []).length;
  if (dotAmount > 1) {
    this.value = $(this).data('lastValidValue');
    return;
  }
  // 规则3:最多3个数字
  const digitAmount = (currentValue.match(/\d/g) || []).length;
  if (digitAmount > 3) {
    this.value = $(this).data('lastValidValue');
    return;
  }
  // 所有规则校验通过,更新合法值缓存
  $(this).data('lastValidValue', currentValue);
}

$('.decimal').on('input', restrictNumber);

HTML 代码(和原有代码一致)

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input class="decimal" type="text">

方案优势

  1. 完全符合要求的三条校验规则:最多3位数字、最多1个小数点、小数点可放在任意位置
  2. 支持正常输入的中间状态,比如输入12.的过程不会被强制拦截,符合用户输入习惯
  3. 逻辑清晰易维护,不需要编写复杂的正则表达式,避免正则匹配遗漏边界场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:24:03