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

JavaScript正则匹配最多3位数字且仅含1个小数点的输入校验求助

问题排查

你编写的正则存在两个核心错误:

  • 外层[]是字符组语法,内部的量词规则(如{0,3})、特殊字符(如.)都会被识别为普通字符,无法实现规则匹配
  • 字符组开头的^是取反含义,会匹配所有不在你指定范围内的字符,和你的需求完全相悖

解决方案

1. 校验正则

根据你的规则(最多3个数字、最多1个小数点、不能仅为小数点),正确的正则如下:

/^(?=(?:\D*\d){1,3}$)(?!.*\..*\.)\d*\.?\d*$/

规则解释:

  • (?=(?:\D*\d){1,3}$):正向预查,限制整个字符串中数字的总数量为1~3个
  • (?!.*\..*\.):负向预查,禁止出现2个及以上的小数点
  • \d*\.?\d*:匹配由数字和最多1个小数点组成的内容

你可以直接用这个正则做提交校验,示例代码:

function checkInputValid(value) {
  const validReg = /^(?=(?:\D*\d){1,3}$)(?!.*\..*\.)\d*\.?\d*$/
  return validReg.test(value)
}

// 测试用例完全符合你的预期
console.log(checkInputValid('333')) // true
console.log(checkInputValid('33.1')) // true
console.log(checkInputValid('3.33')) // true
console.log(checkInputValid('3.3.')) // false
console.log(checkInputValid('3.333')) // false
console.log(checkInputValid('3333.')) // false
console.log(checkInputValid('3..')) // false
console.log(checkInputValid('.')) // false

2. 实时输入限制

如果需要在用户输入时就拦截不符合规则的内容,可以用如下实现:

const inputEl = document.querySelector('#你的输入框选择器')
inputEl.addEventListener('input', function() {
  let val = this.value
  // 第一步:移除所有非数字、非小数点的字符
  val = val.replace(/[^\d.]/g, '')
  // 第二步:移除多余的小数点,仅保留第一个
  const firstDotPos = val.indexOf('.')
  if (firstDotPos !== -1) {
    val = val.slice(0, firstDotPos + 1) + val.slice(firstDotPos + 1).replace(/\./g, '')
  }
  // 第三步:数字总数量超过3个时,截断多余的数字
  const allDigits = val.match(/\d/g) || []
  if (allDigits.length > 3) {
    let digitCount = 0
    val = val.split('').filter(char => {
      if (/\d/.test(char)) {
        digitCount++
        return digitCount <=3
      }
      return true
    }).join('')
  }
  this.value = val
})

内容的提问来源于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 22:45:03