Allow only Numeric in HTML inputbox

In this article, you will see how to allow only numeric (0-9) in HTML inputbox.

Only Numbers allowed : Try this

Following code is used to allow only numeric (0-9).

<input onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">

Another Way

Only Numbers allowed : Try this

Following code is used to allow only numeric (0-9).

<script language="Javascript">
      function isNumber(evt) {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
 
         return true;
      }
</script>
 
<input onkeypress="return isNumber(event)" type="text">

Another Way

Only Numbers allowed : Try this

Following code is used to allow only numeric (0-9).

<script language="Javascript">
     function validate(evt) {
      var theEvent = evt || window.event;
      var key = theEvent.keyCode || theEvent.which;
      key = String.fromCharCode( key );
      var regex = /[0-9]|\./;
      if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
      }
    }
</script>
 
<input onkeypress="return isNumber(event)" type="text">

One Response to Allow only Numeric in HTML inputbox