Explain Codes LogoExplain Codes Logo

How to make an HTML input tag only accept numerical values?

html
input-tag
html5
validation
Nikita BarsukovbyNikita Barsukov·Jan 8, 2025
TLDR

To ensure an <input> tag only accepts numbers, use 'type="number"' or enforce a numeric 'pattern':

<input type="number"> <input type="text" pattern="\d*">

These will block non-numeric input. The type="number" also provides a visually appealing spinner, handy for quantity-based inputs.

For a contingency plan with older browsers, consider the number-polyfill library on GitHub. It does an impressive imitation of the type="number" behavior.

Understanding the HTML5 way of doing things

How to use type="number"

In the wonderful world of HTML5, the type="number" attribute was introduced for <input> tags. This allows us to create input fields specifically designed for numerical values.

Hint: This "number" type does a fantastic job of shielding you from non-numeric rogues! 🛡️💼

Employing the pattern attribute

For the brave souls working with older HTML versions, never fear, the pattern attribute is here! Use it with regular expressions to corral those inputs to only accept numbers.

<input type="text" pattern="[0-9]*" title="Only numbers are allowed">

Reinforcing with JavaScript: Key Event Handling

When you need to double-lock your input field from non-numeric trespassers, call in the heavy artillery – JavaScript:

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

Then team up this function with your input field like so:

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

Now, we have a live-action real-time filter against non-numeric invaders.

Fun fact: ASCII codes between 48 and 57 correspond to 0-9. Everything beyond this range is not a number. Sorry, π.

Dealing with decimals and fancy numeric inputs

For more sophisticated cases like decimal numbers, you can supercharge your JavaScript function to accommodate periods or commas:

function isNumberOrDecimal(evt) { var charCode = (evt.which) ? evt.which : evt.keyCode; // Rock, paper, scissor, or ...decimal? if(charCode == 46 || charCode == 44) { if (this.value.indexOf('.') >= 0 || this.value.indexOf(',') >= 0){ return false; // No double-dipping! } else { return true; } } return isNumberKey(evt); // Redirect to the earlier function }

Trivia: 46 and 44 are ASCII codes for the dot (.) and comma (,), respectively.

JavaScript and jQuery for robust validation

jQuery to enhance ease of validation

jQuery users, rejoice! Here's a streamlined way to ensure that your input fields dispense with any non-numeric characters:

$('input[type="text"]').on('input', function () { this.value = this.value.replace(/[^0-9]/g, ''); });

Fallbacks for non-HTML5 doctypes

For folks dealing with older doctypes, the type="number" or pattern attributes may not come to the rescue. In such instances, a good mix of JavaScript and jQuery can help patrol your input field.

Older Browsers: The wild west

Not all browsers are created equal, though. For older browsers that might not support type="number", you can bring in the cavalry - number-polyfill. Load it conditionally for browsers that need it:

<!--[if lt IE 9]> <script src="path/to/number-polyfill.js"></script> <![endif]-->

Did you know: IE 9 and older do not support type="number". Surprise, I know.

Common pitfalls and fixes

There are a few sneaky ways users can bypass these restrictions:

  1. Users copying and pasting non-numeric values: Control this by adding an onpaste event.
  2. Form auto-fill inputs unexpected values: Use a JavaScript validation on form submission.
  3. Browsers showing incremental arrows for type="number": A bit of CSS magic can style these elements uniformly across browsers.

In-depth learning: Going above and beyond

The HTML Standard and numeric validator tutorials in the References provide a deep dive into the HTML5 behaviour and JavaScript validation techniques.

The provided JSFiddle link offers you a playground to test and tweak to your heart's content.