我似乎无法使用简单的正则表达式。这就是我现在所拥有的:
$(".Hours").on('input', function (e) {
var regex = /^\d+(\.\d{0,2})?$/g;
if (!regex.test(this.value)) {
if (!regex.test(this.value[0]))
this.value = this.value.substring(1, this.value.length);
else
this.value = this.value.substring(0, this.value.length - 1);
}
});
我需要用户只能输入数字和一个小数(小数点后只有两个数字)。它现在正常工作,但用户不能以小数开头。
可接受: 23.53 0.43 1111.43 54335.34 235.23 .53< ---不工作
×: 0234.32< ---用户目前可以这样做 23.453 1.343 .234.23 1.453.23
对此有何帮助?
答案 0 :(得分:10)
RegExp -
^(\d+)?([.]?\d{0,2})?$
解释
Assert position at the beginning of the string «^»
Match the regular expression below and capture its match into backreference number 1 «(\d+)?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below and capture its match into backreference number 2 «([.]?\d{0,2})?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match the character “.” «[.]?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d{0,2}»
Between zero and 2 times, as many times as possible, giving back as needed (greedy) «{0,2}»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
答案 1 :(得分:3)
以下是一条建议:/^((\d|[1-9]\d+)(\.\d{1,2})?|\.\d{1,2})$/
。
允许:0
,0.00
,100
,100.1
,100.10
,.1
,.10
... < / p>
拒绝:01
,01.1
,100.
,.100
,.
......
答案 2 :(得分:1)
这会满足您的需求吗?
var regex = /^\d+([.]?\d{0,2})?$/g;
答案 3 :(得分:1)
你的正则表达式:
var regex = /^\d+(\.\d{0,2})?$/g;
你需要什么:
var regex = /^\d*(\.\d{1,2})?$/;
您要求小数点前至少有一位数(\d+
)。我也改了它,所以如果你包含一个小数,那么它后必须至少有一个数字。
答案 4 :(得分:0)
这将迫使您在小数点分隔符后面添加数字:
^\d+([.]\d)?$
示例:
如果您想输入更多数字; 3代表确保将小数点后的数字的最小值固定为“ 1”
^\d+([.]\d{1,3)?$