输入数字验证 - 仅限输入数字或数字,int &两者都浮动

如何限制输入字段只输入数字/数字 int 和 float 两者.有时我们需要为金额等字段同时允许整数和浮点值,因此在这种情况下需要验证.没有可用的解决方案,但它们的代码很大.所以需要一个简短但有效的代码.

How to restrict the input field to enter only numbers/digits int and float both. Sometimes we need to allow both integer as well as float value for fields like amount, so in that case the validation is required. There are no of solutions available but they are of large size code. So need a short but effective code.

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

推荐答案

号码输入限制不需要长代码,试试这个代码.

No need for the long code for number input restriction just try this code.

它也接受有效的 int &浮动两个值.

It also accepts valid int & float both values.

Javascript 方法

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 />

$(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 />

更新

以上答案适用于最常见的用例 - 将输入验证为数字.

The above answers are for most common use case - validating input as a number.

但根据评论,有些人希望允许一些特殊情况,例如负数和之前向用户显示无效的击键删除它,所以下面是这种特殊用例的代码片段.

But as per comments, some wants to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases.

$(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 />

相关文章