JavaScript Answers

How to Restrict HTML Text Input to Only Allow Numbers?

Spread the love

Sometimes, we only want users to enter numbers into an HTML text input.

In this article, we’ll look at how to restrict HTML text input to only allow numbers.

Watching Keypresses

We can watch keypresses by checking for inputted values and pasted data.

To do this, we write the following HTML:

<input type="text" />

And we can write the following JavaScript:

const input = document.querySelector("input");
input.addEventListener("keypress", (evt) => {
  const theEvent = evt || window.event;
  let key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode(key);
  const regex = /[0-9]|./;
  if (!regex.test(key)) {
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();

We listen to the keypress event with an event listener.

In the keypress event callback, we get the keyCode property to get the code.

Then we get the value of key pressed with String.fromCharCode .

Then we call regex.test to check if the key value is a digit.

If it’s not, then we call preventDefault() to prevent the character from being added to the inputted value string.

Also, we can just remove all the non-digit characters from the inputted value string.

For instance, we can write:

const input = document.querySelector("input");
input.addEventListener("keyup", (evt) => {
  input.value =[^d]/, "");

We get the inputted value with ,.

And we call replace to get all the non-digit characters with an empty string.

Then we assign the returned string to input.value to update the inputted value.

Set Input Type Attribute to number

Also, we can just set the type attribute of input to number .

To do this, we write:

<input type='number' />

Then we don’t need to add any JavaScript code to remove the non-digit characters from the inputted value string.


There’re several ways to restrict an input’s value to digits only.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *