使用整数验证数量

时间:2013-04-16 00:32:39

标签: javascript validation

我正在尝试让我的输入字段只接受整数并编写一些java来帮助验证,但每次我点击下一个输入来插入值时,它都会发出警报。我错过了什么吗?

<script type="text/javascript">
    var cartAmount, subtotal, pstAmount, pstTax, gstTax, taxAmount, shipCharge, afterTax; 

    function validate() {
        //Whole Numbers with Regexp
            var rx = new RegExp(/\d+/);

            if(document.getElementsByClassName("inputValue").value != rx || document.getElementsByClassName("inputValue").value == "") {
                alert("Please use only whole quantities.");
                return false;
            }
    }
    function sumCart() {

        //Adding Cart Values
            cartAmount = (document.frmMain.item1.value * 3.99) + (document.frmMain.item2.value * 5.99); 

        //Finding Subtotals
            document.frmMain.subtotalAmt.value = Math.round(cartAmount*100)/100;
            subtotal = document.frmMain.subtotalAmt.value;

        //Finding Taxes
            pstTax = document.frmMain.taxAmount.value;
            gstTax = .05;

            pstAmount = Math.round((subtotal * pstTax)*100)/100;
            gstAmount = Math.round((subtotal * gstTax)*100)/100;

            taxAmount = parseFloat(pstAmount,10) + parseFloat(gstAmount,10);

            document.getElementById("tax").innerHTML = "Tax in dollars is $" + Math.round(taxAmount * 100)/100;

        //Finding Total
            shipCharge = 0;
            afterTax = parseFloat(subtotal) + parseFloat(taxAmount) + parseFloat(shipCharge);
            document.frmMain.totalAmt.value = Math.round(afterTax*100)/100;
    }
</script>

1 个答案:

答案 0 :(得分:0)

尝试此验证功能:

function validate() {
    //Whole Numbers with Regexp
    var rx = new RegExp(/^\d+$/);
    inputs = document.getElementsByClassName("inputValue");
    for (var i = 0; i < inputs.length; i++) {
        var input = inputs[i].value;
        if (!rx.test(input)) {
           alert("Please use only whole quantities.");
           return false;
        }
    }
}

您的代码有几个问题:

  1. 正则表达式/\d+/只检查该值是否包含任何数字,但不会检查是否有数字。您需要使用^$锚定到开头和结尾,以检查整个值。

  2. 您使用的是value != rx,它不执行正则表达式测试。您必须使用rx.test()

  3. getElementsByClassName返回元素集合,而不是单个元素。您需要循环遍历它们才能获得值。