JavaScript正则表达式,用于带一个点和两个小数的正数 [英] JavaScript Regex for positive numbers with one dot and 2 decimal

查看:69
本文介绍了JavaScript正则表达式,用于带一个点和两个小数的正数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是正则表达式的新手,正则表达式表达有问题。

I am quite new to regex and I have a problem with regex expression.

我只允许用户输入带或不带一个点的正数最多2个小数(也只能是1个小数)。用户在文本框中输入文本后,如果输入的格式错误,我想删除其他字符,并用正确的格式替换值。

I want to only allow a user to enter positive numbers, with or without one dot and up to 2 decimals (can be only 1 decimal also). Upon user typing the text inside the textbox, and if they type the wrong format, I want to remove the other characters and replace the value with the correct format.

有效示例:

123.12
2
56754
92929292929292.12
0.21
3.1
.90

无效示例:

12.1232
2.23332
e666.76
-1.23
-54.3242
3.98A
56B
BBB.12C
14.23.56
1..45

目前,我找到了一种使用以下正则表达式的解决方案:

Currently I found one solution using the following regex :

$("#SomeElement").keyup(function () {
   this.value = this.value.replace(/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2')
});

有两个问题


  1. 它允许我输入多个点。 (例如123.89.80)

  2. 即使我一次输入像字母 a一样,它也会过滤,但是如果我在键盘上按住字母 a,它仍然允许输入(例如AAAAAAAAA12),也许是因为按键事件造成了?

谢谢。

推荐答案

我现在已经对此进行了测试,并且可以运行,试试吧:

I've tested this now and it works, give it a go:

$("#SomeElement").keyup(function () {
    this.value = this.value.replace(/([^\d]*)(\d*(\.\d{0,2})?)(.*)/, '$2');
});

这篇关于JavaScript正则表达式,用于带一个点和两个小数的正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆