输入数字验证-限制为仅输入数字或数字,整型和浮点型(&A;&A)

人气:1,017 发布:2022-10-16 标签: jquery javascript validation floating-point numbers

问题描述

如何将输入字段限制为仅输入数字/数字整型和浮点型。 有时我们需要允许整型和浮点型两种类型的字段,比如Amount,所以在这种情况下需要进行验证。没有可用的解决方案,但它们的代码很大。因此需要一个简短但有效的代码。

<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

推荐答案

不需要长代码来限制数字输入,只需尝试此代码即可。

它还接受有效的整型和浮点型两个值。

Java方法

onload =function(){ 
  var ele = document.querySelectorAll('.number-only')[0];
  ele.onkeypress = function(e) {
     if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
        return false;
  }
  ele.onpaste = function(e){
     e.preventDefault();
  }
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

jQuery方法

$(function(){

  $('.number-only').keypress(function(e) {
	if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
  })
  .on("cut copy paste",function(e){
	e.preventDefault();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

更新

以上答案适用于大多数常见用例--将输入验证为数字。

但根据评论,一些人希望允许少数特殊情况,如 负数向用户显示之前的无效击键(&A; 删除它,因此下面是此类特殊用例的代码片段。

$(function(){
      
  $('.number-only').keyup(function(e) {
        if(this.value!='-')
          while(isNaN(this.value))
            this.value = this.value.split('').reverse().join('').replace(/[D]/i,'')
                                   .split('').reverse().join('');
    })
    .on("cut copy paste",function(e){
    	e.preventDefault();
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

149