only number validation in javascript onkeypress

only number validation in javascript onkeypress Example To accept only alphabets, To accept only numbers without dot, To accept only numbers and dot, To accept only numbers and only one dot and To accept only characters for a username field Examples

only number validation in javascript onkeypress

The simple working script is at the bellow, looks a lot of source code but can be altered to your requirements!

<SCRIPT>

   function validationNum(evt)
   {
      var getNumCd = (evt.which) ? evt.which : event.keyCode;
      if (getNumCd != 46 && getNumCd > 31 
        && (getNumCd < 48 || getNumCd > 57))
         return false;
      return true;
   }

</SCRIPT>
 
    <INPUT id="userDetails" onkeypress="return validationNum(event)" 
           type="text" name="userDetails">

Don’t Miss : How To Allow Only Numbers In Textbox Using Jquery?

If you want to add your input box decimal places add this following source code

<script type="text/javascript">

    var digitsUnique = /[1234567890]/g;
    var integerUnique = /[0-9\.]/g;
    var alphaUnique = /[A-Za-z]/g;
    var usernameUnique = /[0-9A-Za-z\._-]/g;
 
    function validationNum(myfield, e, restrictionType, checkdot){
        if (!e) var e = window.event
        if (e.keyCode) getNumCd = e.keyCode;
        else if (e.which) getNumCd = e.which;
        var character = String.fromCharCode(getNumCd);
 
        if (getNumCd==27) { this.blur(); return false; }
 
        if (!e.ctrlKey && getNumCd!=9 && getNumCd!=8 && getNumCd!=36 && getNumCd!=37 && getNumCd!=38 && (getNumCd!=39 || (getNumCd==39 && character=="'")) && getNumCd!=40) {
            if (character.match(restrictionType)) {
                if(checkdot == "checkdot"){
                    return !isNaN(myfield.value.toString() + character);
                } else {
                    return true;
                }
            } else {
                return false;
            }
        }
    }
</script>
 
<!-- To support only alphabets -->
<input type="text" onkeypress="return validationNum(this, event, alphaUnique);">
<!-- To support only numbers without dot -->
<input type="text" onkeypress="return validationNum(this, event, digitsUnique);">
<!-- To support only numbers and dot -->
<input type="text" onkeypress="return validationNum(this, event, integerUnique);">
<!-- To support only numbers and only one dot -->
<input type="text" onkeypress="return validationNum(this, event, integerUnique, 'checkdot');">
<!-- To support only characters for a username field -->
<input type="text" onkeypress="return validationNum(this, event, usernameUnique);">

I hope you get an idea about only number validation in javascript onkeypress.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.