javascript - 正则表达式验证 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
解决方案
假设您在输入时正在验证。只需向用户发出信号是否正常。下一个片段在输入时检查给定的输入,向用户发出信号,并在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>
推荐阅读
- html - 引导三个垂直输入组
- google-sheets - 非连续范围的条件格式
- html - ::before 带有 :hover 效果的语法
- scala - 安装 ADLS - 范围内不存在秘密:
和关键: - python - ImportError:尝试使用 pip 时无法导入名称“FormatControl”
- json - Ansible,使用变量修改主机和端口
- mysql - MySQL 选择 col1 (int) 的值为 2 OR 3 AND col2 (tinybit) = 0
- intellij-idea - 如何增加 IntelliJ 中悬停文档的超时时间?
- python - ValueError:“conv3d_3/convolution”(操作:“Conv3D”)从 1 中减去 22 导致的负尺寸大小
- jquery - 动态下拉菜单不做条件语句