javascript - 验证 HTML 数字输入

标签 javascript

如何验证必须包含 1.00 或更大值的字段?还必须包含 2 位小数。

我发现了这个......

    <input pattern="\d?\d\.\d\d" maxlength=5 size=5 onchange="check(this)">
    <script>
    function check(elem) {
      if(!elem.value.match(/^\d?\d\.\d\d$/)) {
        alert('Error in data – use the format dd.dd (d = digit)');
      }
    }
    </script>

但它不允许超过 99.99 的值。

抱歉,我需要添加更多详细信息来解释这一点。

我需要接受 1.00 或 10.00 甚至 1000.00

只是没有

1 或 10 或 2.0 或 20.0

必须是整数和小数点后两位

非常感谢任何帮助!

最佳答案

/^[1-9]+\d*\.\d{2}$/g 应该在哪里工作

^[1-9] : makes sure the non-decimal part is greater than 0.
\d*    : allows trailing zeroes as in 1000

const regex = /^[1-9]+\d*\.\d{2}$/g;
const str = `1601.91`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

关于javascript - 验证 HTML 数字输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44642804/

相关文章:

javascript - 日期对象和 UTC 方法

javascript - 异步/等待失败的 Angular promise

javascript - JS : how to capture output of a function every time it gets called

javascript - 在 while 循环中嵌入 Optgroup 的选择组

javascript - jQuery:通过单击 DIV 本身以外的任何地方来关闭 DIV?

javascript - 在 AngularJS 中保存大量数据

javascript - 在嵌套对象数组中按属性路径查找对象

javascript - Filepicker IO如何指定上传的最小宽度和高度

javascript - 序列化 JavaScript 对象

javascript - Nuxt 项目中未加载 JS 文件