Javascript - validation, numbers only

前端 未结 14 1687
感动是毒
感动是毒 2020-12-08 09:52

I\'m trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number,

相关标签:
14条回答
  • 2020-12-08 10:33
    var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
    for (i = 0; i < elem.length; i++) {
       elem[i].addEventListener('keypress', function(event){
          var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
          var validIndex = keys.indexOf(event.charCode);
          if(validIndex == -1){
             event.preventDefault();
          }
      });
    }
    
    0 讨论(0)
  • 2020-12-08 10:35

    here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313

    <input type="text" 
    onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
    />
    

    and this will not accept entering the dot (.), so it will only accept integers

    <input type="text" 
    onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
    />
    

    this way you will not permit the user to input anything but numbers

    0 讨论(0)
  • 2020-12-08 10:35

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

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

    0 讨论(0)
  • 2020-12-08 10:39

    This one worked for me :

    function validateForm(){
    
      var z = document.forms["myForm"]["num"].value;
    
      if(!/^[0-9]+$/.test(z)){
        alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
      }
    
    }
    
    0 讨论(0)
  • 2020-12-08 10:40

    The simplest solution.

    Thanks to my partner that gave me this answer.

    You can set an onkeypress event on the input textbox like this:

    onkeypress="validate(event)"

    and then use regular expressions like this:

    function validate(evt){
         evt.value = evt.value.replace(/[^0-9]/g,"");
    }
    

    It will scan and remove any letter or sign different from number in the field.

    0 讨论(0)
  • 2020-12-08 10:40

    // I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:

    $(document).ready(function () {
           $(".nosonly").keydown(function (event) {
               // Allow only backspace and delete
               if (event.keyCode == 46 || event.keyCode == 8) {
                   // let it happen, don't do anything
               }
               else {
                   // Ensure that it is a number and stop the keypress
                   if (event.keyCode < 48 || event.keyCode > 57) {
                  alert("Only Numbers Allowed"),event.preventDefault();
                   }
               }
           });
       });
    
    0 讨论(0)
提交回复
热议问题