Explain Codes LogoExplain Codes Logo

Prevent typing non-numeric in input type number

javascript
event-listeners
input-validation
regular-expressions
Alex KataevbyAlex Kataev·Mar 2, 2025
TLDR

Here's the quickest way to restrict an input[type="number"] to numeric characters only. Apply a JavaScript input event listener to erase any non-digit character as soon as it's input.

document.querySelector('input[type="number"]').addEventListener('input', function(e) { e.target.value = e.target.value.replace(/\D+/g, ""); // Sayonara, non-digits! });

Waiving the magic wand of event listeners

User input is like a box of chocolates, you never know what you're gonna get. Validate and correct it in real time with JavaScript's event listeners like keypress, keydown, keyup, input.

  • keypress lets you intercept and cancel an input before it's processed.
  • keyup offers a chance for a post-mortem analysis and correction.
  • input gives you 'live updates' from the user's input, ideal for proactive filtering.

Keeping the evil non-numerics at bay with keypress

Want to prevent non-numeric characters from materialising on the screen as they're typed? Enlist the keypress event. It's your Gandalf on the bridge declaring "You shall not pass!" to non-numerics.

document.querySelector('input[type="number"]').addEventListener('keypress', function(e) { // Another '.'? Nice try, Sauron! if (e.key === '.' && this.value.includes('.')) { e.preventDefault(); } // What is this strange creature? Not a digit! else if (!/[0-9]/.test(e.key)) { e.preventDefault(); } });

This doesn't just prevent non-numeric characters but also curbs the creation of duplicate decimal points, making the input more reliable.

After-the-fact clean-up with keyup

keyup event fires after the ghost of the key pressed has left the building. With it, you get another chance at catching and fixing naughty non-numeric inputs.

document.querySelector('input[type="number"]').addEventListener('keyup', function(e) { this.value = this.value.replace(/[^0-9.]+/g, ''); // It's never too late for a clean-up! });

This helps especially when someone tries to cheat the system by pasting inappropriate characters into the input.

Making peace with browser inconsistency - It's not you, it's me

While web browsers agree on a lot of things, they sometimes have their quirks when it comes to interpreting keypress and keyup events. To stay ahead, you can use e.key property which offers better compatibility across modern browsers:

document.querySelector('input[type="number"]').addEventListener('keypress', function(e) { const allowedKeys = /[0-9]|\./; if (!allowedKeys.test(e.key) || (e.key === '.' && this.value.includes('.'))) { e.preventDefault(); // Do I look like a text field to you? } });

This helps ensure consistent behaviour irrespective of the browser.

Avoiding accidental treason - Respect control keys

In your quest to oust non-numeric characters, be careful not to wage a war against essential control keys such as arrow keys, backspace, and ctrl/cmd+Key operations.

document.querySelector('input[type="number"]').addEventListener('keydown', function(e) { if (!e.ctrlKey && !e.metaKey && !/[0-9]/.test(e.key) && e.key !== 'Backspace' && e.key !== 'Delete' && e.key !== 'ArrowLeft' && e.key !== 'ArrowRight' && e.key !== 'Tab') { e.preventDefault(); // Control keys are our allies } });

This way, you're restraining non-numeric inputs without disrupting essential input facility.

Being the lord of the edge cases

Here's a cheat sheet for outsmarting the edge cases:

  • Copy-pasting non-numeric text: Opportunities aplenty with keyup or input events for cleaning it up.
  • Browser autofill: Staying a step ahead of the browser when it has its own plans.
  • Accessibility and mobile device compliance: Be mindful of the needs of screen readers and mobile keyboards.

The art and science of crafting regular expressions

An efficiently written regular expression is not just elegant, it also makes your code easier to maintain and debug.

const numberPattern = /^\d*\.?\d*$/; // A number; may have a '.' somewhere, but don't quote me on that.

This concise pattern is self-explanatory and easy to remember, making it a handy tool for future developers.

Friendly advice

Remember:

  • keypress and key behaviours might differ across browsers. Test extensively, trust sparingly.
  • input of type="number" doesn't always reflect non-numeric characters. input events are your faithful mirrors when in doubt.
  • HTML5 validation is still handy with pattern attribute, even on type="number" inputs.
  • Empathise with web accessibility. Inclusivity is your magic charm.