首页 > 解决方案 > 正则表达式验证 3 位数字和带小数点的两位小数

问题描述

我目前正在使用这个正则表达式:^\d{1,3}(\.\d{1,2})?$正如这里的问题中提供的那样:正则 表达式最多 3 个整数和 2 个小数

这在正则表达式测试器中运行良好,并且与模式匹配。我遇到的问题是在验证输入并防止除 3 位和 2 位小数之外的任何内容时,该模式不允许在 2 位小数之前使用 3 位和 1 位小数,例如

234.34被允许

234.不被允许

我目前无法在小数点后输入任何内容,因为它是基于模式被阻止的。我想在三位数字后输入一个小数,它与小数点后的 2 位数字匹配,并且不匹配小于 1,例如

allowed

1
2.
2.3
2.38
22.
22.2
22.38
234. 
234.2 
234.34 

not allowed

0.2
0.23
00.23
000.23
234.255

标签: javascriptregextypescript

解决方案


假设您在输入时正在验证。只需向用户发出信号是否正常。下一个片段在输入时检查给定的输入,向用户发出信号,并在data-ok=0/1输入上设置一个数据属性 (),可用于进一步处理。它使用事件委托进行keyup处理。

document.addEventListener(`keyup`, handle);

function handle(evt) {
  if (evt.target.id === `nr`) {
    const rawVal = evt.target.value;
    const [int, dec] = rawVal.split(`.`);
    const cando = /[^.]$/.test(rawVal) && 
      /^[0-9]{1,3}$/.test(int) && 
      !dec || /^[0-9]{1,2}$/.test(dec);
    document.querySelector(`#check`).textContent = cando ? `OK!` : `NOT OK`;
    evt.target.dataset.ok = +cando;
  }
}
body {
  font: normal 12px/15px verdana, arial;
  margin: 2em;
}

#check {
  color: red;
}
<input type="text" id="nr"> enter number (max 1000)  
<span id="check"></span>

<p>
  You may also check the possibility of using
  <a target="_blank" 
    href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number"
  >numeric input</a>
  <input type="number" id="numeric" 
    min="0" 
    max="999.99" 
    step="0.01"
    placeholder="0 - 999.99">
    
    <span id="checknr"></span>
</p>


推荐阅读