使用javascript验证文本框中带小数值的数字

时间:2012-03-28 13:52:13

标签: javascript textbox

如何限制用户只使用javascript ??

在文本框中输入6位数字和2位小数值
//Function to allow only numbers to textbox
function validate(key) {
    //getting key code of pressed key
    var keycode = (key.which) ? key.which : key.keyCode;
    var phn = document.getElementById('txtPhn');
    //comparing pressed keycodes
    if ((keycode < 48 || keycode > 57)) {
        return false;
    } else {
        if (phn.value.length < 6) {
            return true;
        } else {
            return false;
        }
    }
}

编辑:

var txtBudget = document.getElementById('MainContent_txtBudget');
    txtBudget.addEventListener('input', function (prev)
     {
        return function (evt) {
            if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(this.value)) {
                this.value = prev;
            }
            else {
                prev = this.value;
            }
        };
    } (txtBudget.value), false);

2 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

var foo = document.getElementById('foo');

foo.addEventListener('input', function (prev) {
    return function (evt) {
        if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(this.value)) {
          this.value = prev;
        }
        else {
          prev = this.value;
        }
    };
}(foo.value), false);​

代码不符合跨浏览器标准,但它应该为您提供一些如何完成的提示。

演示:http://jsfiddle.net/v4tGc/


更新:未使用输入事件。

var foo = document.getElementById('foo');

foo.addEventListener('keypress', function (evt) {
    var value = this.value + String.fromCharCode(evt.which);
    if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(value)) {
      evt.preventDefault();
    }
}, false);​

答案 1 :(得分:0)

**When I Googling, found a code. And then i modify to what i need. And I think it will help you**.

    **HTML**

        <html>
            <head>
                <meta charset="utf-8">
                <title>JS Bin</title>
            </head>
            <body>
                <input type="text" id="sal" name="sal" onkeypress="return isDecimalNumber(event,this)">
            </body>
        </html>

    **Javascript**



<script type="text/javascript">

            function isDecimalNumber(evt, c) {
                var charCode = (evt.which) ? evt.which : event.keyCode;
                var dot1 = c.value.indexOf('.');
                var dot2 = c.value.lastIndexOf('.');

                if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
                    return false;
                else if (charCode == 46 && (dot1 == dot2) && dot1 != -1 && dot2 != -1)
                    return false;

                return true;
            }

        </script>