2012-03-28 50 views
0

如何限制用户输入只有6位数字和两个十进制值在文本框中使用JavaScript?验证使用javascript的文本框中的十进制数字

//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); 
+0

注意要覆盖键码96 - 105,这是数字小键盘。您还应该覆盖退格,制表符和箭头键。 – 2012-03-28 14:13:52

回答

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

如何在文本框的onkeypress事件中调用这个函数? – kk1076 2012-03-28 14:21:33

+0

看看我的编辑。 – kk1076 2012-03-28 14:21:47

+0

我已经尝试过这样,但它不工作 – kk1076 2012-03-28 14:24:11

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>