Input number validation - Restrict to enter only numbers or digits, int & float both

前端 未结 6 2069
迷失自我
迷失自我 2020-12-03 03:50

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

6条回答
  •  余生分开走
    2020-12-03 04:52

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

    It also accepts valid int & float both values.

    Javascript Approach

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

    Input box that accepts only valid int and float values.

    jQuery Approach

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

    Input box that accepts only valid int and float values.

    UPDATE

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

    Input box that accepts only valid int and float values.

提交回复
热议问题