javascript - 检查小数点前 4 个数字和小数点后 1 个数字

标签 javascript regex

我有一个输入数字字段,它应该允许最多 4 个小数点前的数字和最多 1 个小数点后的数字或最多 6 个没有小数点的数字。 例如。有效 1.2、113.5、1234.5、456789。

我在按键上使用了这个 RegEx ^\d{0,4}\.?(\.\d{0,1})?$。它工作正常,但只有在显示 113.55 之类的数字后才会给出 false。我该如何解决这个问题?

我的按键功能:

函数 OnKeyPress(e,DivID) {

            if ( e.which != 8 && e.which != 0  && e.which != 13 && e.which != 46 && (e.which < 48 || e.which > 57)) {
                        return false;
            }

            var val = j$('[id$='+DivID+']').val();


            if(DivID == 'ProximityCPPercentage')
            {
                var x = event.which || event.keyCode;
                if(val.indexOf('.') >= 0 && e.which == 46)
                    return false;
                else if(e.which == 46 && val.length == 3)
                    return false;
                if(val.indexOf('.') == 0)
                    val = '0' + val;
                if(e.which != 46)
                {                        
                    strval = val + String.fromCharCode(x);
                    var re = /^((.|0|[1-9]\d?)(\.\d{1})?|100(\.0?)?)$/;
                    if(!re.test(strval))
                        return false;
                }
            }              
            else if(val.indexOf('.') > 0)
            {
                if(e.which == 46 )
                    return false;
                var arra = val.split('.');
                var decval = arra[1];

                var val = arra[0];
                if(val.length > 6)
                    return false;
                if(decval.length > 0)
                    return false;                        
            }                
            else if(e.which != 46 )
            {
                if(val.length > 5)

                    return false;
            }

        }

最佳答案

使用下面的正则表达式

^\d{0,4}([.\d]\d)?$

Regex explanation here

Regular expression visualization


如果您不想匹配 5 位数字,请使用 negative look-ahead assertion为了避免这种情况

^(?!\d{5}$)\d{0,4}([.\d]\d)?$

Regex explanation here

Regular expression visualization

关于javascript - 检查小数点前 4 个数字和小数点后 1 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38149692/

相关文章:

javascript - 捕获 JavaScript console.log console.dir、console.table

javascript - 括号中的点用于访问嵌套属性

javascript - 如何在确认弹出窗口中对齐新行? (JavaScript)

regex - 正则表达式 `## Example[^]+### Response` 无法匹配

python - python 正则表达式分组的最佳实践

javascript - 正则表达式 - 匹配一个没有空格的字符串

javascript - 使用 D3 制作没有 mustache 的彩色箱线图

javascript - JS 在 es6 中声明并分配多变量?

php - 将反引号转换为 '<code>' 和 '</code>' 的最简单方法是什么?

regex - Atom 中的自定义语法高亮显示