输入数字验证 - 限制只输入数字或数字,int和float两者

vin*_*akj 8 javascript floating-point validation jquery numbers

如何限制输入字段只输入数字/数字int和浮动两者.有时我们需要允许像amount这样的字段的整数和浮点值,因此在这种情况下需要验证.没有可用的解决方案,但它们具有大尺寸代码.因此需要一个简短但有效的代码.

<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
Run Code Online (Sandbox Code Playgroud)

vin*_*akj 16

不需要数字输入限制的长代码只需尝试此代码.

它还接受有效的int和float两个值.

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();
  }
}
Run Code Online (Sandbox Code Playgroud)
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
Run Code Online (Sandbox Code Playgroud)

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();
  });

});
Run Code Online (Sandbox Code Playgroud)
<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 />
Run Code Online (Sandbox Code Playgroud)

UPDATE

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

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

$(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();
    });

});
Run Code Online (Sandbox Code Playgroud)
<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 />
Run Code Online (Sandbox Code Playgroud)


cli*_*ait 10

单线解决方案#1:

<input type="number">step属性一起使用.

<input type="number" step="0.0001"> // The user can enter up to 4 decimal places.

<input type="number" step="any"> // Not supported in all browsers, but permits numbers of any decimal precision.
Run Code Online (Sandbox Code Playgroud)

您还可以使用min和/或max属性设置最小值和/或最大值.


单线解决方案#2:

使用input带有RegExp pattern属性的常规文本元素.

<input type="text" pattern="^-?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)$">
Run Code Online (Sandbox Code Playgroud)

此RegExp接受以点(.)和/或负号(-)开头的数字.

  • 这个答案只是一个脚注.此输入类型仅在HTML5中有效,[当前html5标记支持](http://www.quirksmode.org/html5/inputs/) (3认同)
  • 这里几乎没有重要的事情:1.这就是HTML5功能2.每个浏览器的外观和感觉是不同的3.随时随地验证不可用4.对于提交过的验证,你必须有表格标签包含这个.5.所有浏览器的错误消息都不相同 (2认同)