How to Limit the User to Typing Only Numeric Values in a TextBox Using JavaScript


Every developer needs to use numeric validation in input fields on the client-side, in other words somewhere the client wants that 2 input fields should be numeric and no end-user can fill a value in other than numerics, like letters, special characters and so on. In that case, you can use JavaScript to disable the action of unwanted keys via the "onkeypress" event. 
Some input fields like Roll number, Login ID, and so on needs this kind of validation.
To create a sample to explain such implementation, I will use the following procedure.
Step 1
Create an ASP.Net Empty Website named "My Project".
create empty web Site
Step 2
Add a new web form named "Default.aspx" into it.
add web form
Step 3
Add a "TextBox" control for Login ID in the page named "Default.aspx" .
Login ID
Step 4
Write a function in JavaScript that will get the ACSII code of the key pressed by the user and that will return "true" if it's a numeric otherwise "false".
  1. function ValidNumeric() {    
  3.     var charCode = (event.which) ? event.which : event.keyCode;    
  4.     if (charCode >= 48 && charCode <= 57)    
  5.     { return true; }    
  6.     else    
  7.     { return false; }    
  8. }   
Note- The ASCII code of numeric values lie between 48 and 57.
Step 5
Now to call the function of JavaScript on the "onkeypress" event of the TextBox.
  1. <asp:TextBox ID="txtLoginID" runat="server"     
  2.    onkeypress="return ValidNumeric()">    
  3. </asp:TextBox> 


In this article, I have described how to limit the user to typing only numeric values and I hope it will be beneficial for you.