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 2 input fields should be numeric and no end-user can fill in a value 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 "on keypress" event.

Some input fields like Roll number, Login ID, and so on need 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".

My Project

Step 2. Add a new web form named "Default.aspx" into it.

Add web form

Step 3. Add a "TextBox" control for the Login ID on the page named "Default.aspx".

Login ID

Step 4. Write a function in JavaScript that will get the ASCII code of the key pressed by the user and that will return "true" if it's a numeric otherwise "false".

function ValidNumeric() {   
    var charCode = (event.which) ? event.which : event.keyCode;   
    if (charCode >= 48 && charCode <= 57)   
    { return true; }   
    { return false; }   

Note. The ASCII code of numeric values lies between 48 and 57.


Step 5. Now call the function of JavaScript on the "on keypress" event of the TextBox.

<asp:TextBox ID="txtLoginID" runat="server" onkeypress="return ValidNumeric()"></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.