Categories
JavaScript Answers

How to restrict a text field to numbers only with JavaScript?

Spread the love

To restrict a text field to accept only numbers using JavaScript, you can use the onkeypress event to validate each key pressed by the user.

For example we write

<input type="text" id="numberField" onkeypress="return isNumberKey(event)">

to an input.

And here’s the JavaScript function to enforce the restriction:

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

In this code, the isNumberKey() function checks if the key pressed is a number.

It uses event.which or event.keyCode to determine the key code of the pressed key.

If the key code is not within the range of numbers (48 to 57 for digits 0-9), it returns false, preventing the input.

This method will ensure that only numeric characters are allowed in the text field.

However, keep in mind that users can still paste non-numeric text into the field unless you additionally handle the onpaste event to prevent this.

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 *