Restrict User to enter numeric value in textbox using javascript

Restrict User
Restrict User

Restrict User to enter a numeric value in textbox

Hi Readers, In this blog, I am going to discuss how can we Restrict User to input only number in the textbox.Sometimes when we create a form and we have fields like mobile number and zip code.where we want Restrict User to only input number.

For this, you have basic knowledge about Html and Javascript.I have explained you this tutorial step by step.First, I have explained about HTML code and how to call a javascript function.When a user presses the key and then created a javascript function to restrict users so that it can only input numbers in a textbox.

 

 

Html Code To Restrict User

In this code, I have taken a textbox and when user click on textbox then it will call isNumberKey() Function.This function is customise function built in javacript to Restrict User to input only number on the basis of key pressed by user.

 <INPUT id="txtMobile" onkeypress="return isNumberKey(event)" 
           type="text" name="txtMobile">

 

Javascript Code To Restrict User

Here I have created a function with name isNumberKey.In this function first I get the keycode of the user’s input and then check keycode is in 0-9 series or not.If not then function return false.

48-57(0-9)

function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
       }

 

Full Code

<HTML>
  <HEAD>
<title>Restrict User</title>

    <SCRIPT>
       <!--
       function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
       }
       //-->
    </SCRIPT>
  </HEAD>
  <BODY>
    <INPUT id="txtMobile" onkeypress="return isNumberKey(event)" 
           type="textMobile" name="txtChar">
<p>Above text box take only integers not string</p>
  </BODY>
</HTML>

I hope you would like this session about  Restrict User to input only Number

Leave a Comment