Explain Codes LogoExplain Codes Logo

Html text input allow only numeric input

html
input-validation
numeric-input
html5-inputs
Alex KataevbyAlex Kataev·Sep 20, 2024
TLDR

Enforce numeric-only input in HTML text fields with specific attributes. Apply this code snippet for a quick fix:

<input type="text" oninput="this.value=this.value.replace(/[^0-9]/g,'')">

This employs the oninput event to continuously exclude non-numeric characters employing JavaScript, invoking a regular expression (/[^0-9]/g) to replace non-digits. Consequently, real-time validation ensures numeric input without relying on form submission or other validation procedures.

Holistic numeric input management: the what, why, and how

Server-side validation: to trust or not to trust client-side validation

Put no trust in client-side validation alone. Always re-verify the data on the server. Even the not-so-savvy, but tricky users are capable of bypassing JavaScript validation.

Decimal points and leading zeros: a tale of two siblings

To allow decimals and get rid of excess decimal points, here's an enchanted incantation:

this.value = this.value.replace(/[^0-9.]|(?<=\..*)\./g, '') .replace(/^0+/, '0') .replace(/^0(?=[1-9])/, '');

This spell allows for a single decimal point and corrects leading zeros, ensuring inputs like 0.123 stay rich, while turning 000123 into a more minimalistic 0123.

Unleashing the power of HTML5 inputs

The magic of <input type="number">

Think about replacing <input type="text"> with <input type="number"> to channel the innate validation powers of HTML5. But be sure to tread carefully, for the behavior of browsers can be unpredictable.

Tripping over browser inconsistencies

In the wild landscape of browsers, Chrome begrudgingly accepts 'e' and 'E' characters in type="number" as exponential input, while Firefox and Edge might have their own unique allowances for non-numeric characters.

The art of creating better user experiences

For enhanced user-friendliness, add the required attribute for fields that cannot be left empty and utilize valueAsNumber to access the numerically-typed value, thus bypassing JavaScript's usual string conversion:

<input type="number" required oninput="this.valueAsNumber = this.validity.badInput ? '' : this.valueAsNumber">

Knowing the extra miles and how to cover them

Custom feedback for invalid input: because everyone deserves to know the truth

Present users with immediate feedback and possibly a custom message when they type invalid characters. This can be achieved by using .classList and setCustomValidity:

function validateInput(input){ if (input.validity.patternMismatch){ input.classList.add('input-error'); //Presumes `.input-error` class got its fashion sense from the 80s. Bright red and bold! 💅 input.setCustomValidity('Only numeric values are allowed.'); } else { input.classList.remove('input-error'); // Was it something I said? input.setCustomValidity(''); } input.reportValidity(); }

JSFiddle to the rescue

Try out real-time demos on JSFiddle for hands-on experience and insights. It provides a sandbox environment for a hands-on understanding of various data-type input filters.

Key handling for the matrix

Manage more complex scenarios by attaching event handlers to keydown, keypress, and keyup events. Special keys such as Backspace, Arrow keys, and Tabs demand royal treatment and thus, need exceptional handlers.

function setInputFilter(inputElement, inputFilter) { ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) { inputElement.addEventListener(event, function() { if (inputFilter(this.value)) { // When the clock strikes the midnight hour this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { // Those were the days, my friend this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } }); }); } // Use the function setInputFilter(document.getElementById("myNumericInput"), function(value) { return /^\d*\.?\d*$/.test(value); // To be a number, or not to be a number, that is the question });

The secret diary of keys: a numeric tale

Take note of keycodes and restrict numeric input to allow number inputs from the keypad as well as the keyboard:

function isNumericKeyEvent(event) { let key = event.keyCode;// It's not just a number, it's an identity. return ((key >= 48 && key <= 57) || // The folks from the top row (key >= 96 && key <= 105)); // The party animals from the nums pad } inputElement.addEventListener('keydown', function(event) { if (!isNumericKeyEvent(event)) { // "Sorry, you ain't on the list. Can't enter the club!" event.preventDefault(); } });