Allow only numbers in textbox, Allow only numbers in textbox Javascript

[Resolved]: Allow only numbers in textbox Javascript | asp.net, HTML, Javascript

There are situations while working with a webpage using plain HTML/Javascript/asp.net c# to allow only numbers in textbox. There are two solutions for this, choose the best suitable for your need.

  • Using plain javascript code.
  • Using built-in Regular expression validator.

Answer 1:

Allow only numbers in textbox Javascript

If we look at below code, we are going to make use of HTML and javascript code. we have created a textbox with id “txtChar” in HTML body tag and “isNumberKey(evt)” function in javascript code. The key logic how this works is based on event named “onkeypress“.

I have created an “onkeypress” event passing the key pressed as a parameter to a javascript code and “isNumberKey(evt)” function will validation whether this key is number or not.

Below is the example code to allow only numbers in a textbox javascript.

Example:

Answer 2:

Code to allow only numbers in textbox using Regular Expression Validator in ASP.NET

This solution will be quiet straightforward. Using the regular expression validator in asp.net controller on the toolbar, drag and drop to the required form. Next, we can make use of the property ValidationExpression for validating the user input using regex expression (“\d+“). To make sure only integers are allowed in the textbox.

Example code to allow only numbers in a textbox using regular expression validator in asp.net c# is below.

Example Code: