仅输入数字,但在开头输入“-”

时间:2019-02-22 09:46:22

标签: jquery

我只需要阻止数字输入。我还只需要允许- 1次,并且如果允许的话,也只能在开始时允许。

这是我现在可以很好运行的脚本:

$('#sss').on('input', function() {
  this.value = this.value
    .replace(/[^\d.-]/g, '')             // numbers and decimals only and negative
    .replace(/(^[\d]{3})[\d]/g, '$1')   // not more than 3 digits at the beginning
    .replace(/(\..*)\./g, '$1')         // decimal can't exist more than once
    .replace(/(\.[\d]{2})./g, '$1');    // not more than 2 digits after decimal
});

提琴:https://jsfiddle.net/jz60p7xn/1/

我不知道如何编辑代码。尝试添加:.replace(/(\-*)\./g, '$1'),但没有成功。

所以:

2.345 wrong
1234.43 wrong
2 ok
123.00 ok
-123.00 ok <--- attention at this cause i've set a number digit of 3 at beginning, so if "-" is present i don't know if rules works great
--2 wrong
2.00- wrong
23.-54 wrong

1 个答案:

答案 0 :(得分:1)

如果您确实想走字符串操作路线,则可以将字符串开头的-不是 的字符串与模式(?!^)-相匹配:< / p>

$('#sss').on('input', function() {
  this.value = this.value
    .replace(/[^\d.-]/g, '')            // numbers and decimals only and negative
    .replace(/(?!^)-/g, '')             // allow - only at the beginning
    .replace(/^(-?\d{3})\d+/, '$1')     // not more than 3 digits at the beginning
    .replace(/(\..*)\./g, '$1')         // decimal can't exist more than once
    .replace(/(\.[\d]{2})./g, '$1');    // not more than 2 digits after decimal
});

或者,您可以考虑只使用<input type="number">