Javascript 如果夹紧按钮,货币验证不起作用

Javascript currency validation doesn't work if clamp button

我想根据以下要求验证我的输入:

  1. 值可以从 1.00 到 9999.99
  2. 值的小数部分不能超过 2 位

我写了下面的代码:

html:

<input id="amount" maxlength="7" type="text" />

js:

$("#amount").on("keyup", function(){
    var valid = /^[1-9]{1}\d{0,3}(\,\d{0,2})?$/.test(this.value),
        val = this.value;

    if(!valid){
        console.log("Invalid input!");
        this.value = val.substring(0, val.length - 1);
    }
});

但如果我钳制“0”,效果会很差。

请帮忙修复[​​=15=]

JSFIDDLE

P.S.

如果我按“0”3-4 秒,我会看到

预期结果 - 所有输入都清楚

$(".allownumericwithdecimal").live("keypress keyup ",function (event) {
    var text = $(this).val(); 
    $(this).val($(this).val().replace(/[^0-9\.]/g,''));  



    if(text.indexOf('.') != -1 && event.which==190 )
    {   
        if(text.match("^[0-9]+(\.[0-9]{0,2})?$")){
        }
        else{
            $(this).val('') ;
        }
    }
     if(text.indexOf('.') == -1 && text.length>7 && (event.which!=190 && event.which !=8 && event.which !=46 && event.which !=110 && event.which !=0)){
         event.preventDefault();
     }
});

$(".allownumericwithdecimal").live("blur",function (event){
    var text = $(this).val(); 
    if((text.indexOf('.') != -1)){  
        if((text.substring(text.indexOf('.'), text.indexOf('.').length).length)>2){
            text = text.toString(); //If it's not already a String
            text = text.slice(0, (text.indexOf("."))+3); //With 3 exposing the hundredths place
            $(this).val(text);
        }
    }
});

这是我个人使用的

我已经更新了您的正则表达式,所以现在它可以正常工作了。

演示:http://jsfiddle.net/vY39r/391/

$("#amount").on("input", function(){
    var valid = /^[0-9]{1}\d{0,3}(\.\d{0,2})?$/.test(this.value),
        val = this.value;

    if(!valid){
        console.log("Invalid input!");
        this.value = val.substring(0, val.length - 1);
    }
});

希望对您有所帮助。

$("#amount").on("input", function(){
    var valid = /^[1-9]{1}\d{0,3}(\.\d{0,2})?$/.test(this.value),
        val = this.value;

    if(!valid){
        console.log("Invalid input!");
        this.value = val.substring(0, val.length - 1);
    }
});

http://jsfiddle.net/a2eqrquf/

我的正则表达式不是很准确,所以有人可能比我更能整理一下。但这是应该的。

这是输入的数字,只需要使用以下 HTML:

<input id="money-input" type="number" value="1" min="1" max="9999.99" step="0.01">

如果您想限制可以输入的小数位数,您只需在数字的四舍五入处添加一些 JavaScript:

(function() {
    var input = document.getElementById('money-input');

    input.addEventListener('blur', function() {
        this.value = Math.round(this.value * 100) / 100;
    });
})();