How to prevent typing non-numeric characters in input-type numbers with JavaScript?

Estimated read time 2 min read

To prevent typing non-numeric characters in an input with the type="number" attribute, you can listen for the keypress event on the input element, and then check if the key pressed is a numeric character or a special character that is allowed (e.g. the period character for decimal numbers). If the key pressed is not a numeric or allowed special character, you can prevent it from being entered into the input using the preventDefault() method. Here’s an example of how to do this:

const numericInput = document.getElementById('myNumberInput');

numericInput.addEventListener('keypress', function(event) {
  const key = event.key;

  if (isNaN(key) && key !== '.' && key !== '-' && key !== '+') {
    event.preventDefault();
  }
});

In this code, we add an event listener to the numericInput element for the keypress event. Inside the event listener function, we get the character that was typed using the event.key property.

We then check if the character is a numeric character using the isNaN() function, which returns true if the character is not a number. We also check if the character is the period character (for decimal numbers), or the minus or plus characters (for negative and positive numbers, respectively), and allow those characters.

If the character is not a numeric or allowed special character, we prevent it from being entered into the input using the preventDefault() method on the event object.

Note that this code will only prevent non-numeric characters from being typed into the input field. It does not prevent the user from pasting non-numeric characters into the input field. If you want to prevent pasting non-numeric characters, you can add an event listener for the paste event and check the contents of the clipboard before pasting it into the input field.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply