Restricting a text input to digits (0-9) requires combining HTML attributes with an input event listener. Relying on keydown alone misses pastes, drag-and-drop, autofill, and mobile keyboards, while sanitizing on input (plus validating on submit) keeps the value clean across devices.
1. HTML Attributes + input Event Sanitization
Start with type="text", inputmode="numeric", and pattern="[0-9]*" for a numeric mobile keypad and basic HTML5 pattern validation, then strip non-digits on input:
<input
id="otp-input"
type="text"
inputmode="numeric"
pattern="[0-9]*"
autocomplete="one-time-code"
maxlength="6"
/>
<script>
const digitsInput = document.querySelector("#otp-input");
digitsInput.addEventListener("input", () => {
const cleaned = digitsInput.value.replace(/\D+/g, "");
if (digitsInput.value !== cleaned) {
digitsInput.value = cleaned;
}
});
</script>
2. Preserving Cursor Position and Handling Edge Cases
Overwriting input.value when editing in the middle of a string can jump the caret to the end. If users frequently edit mid-string, restore the caret offset relative to how many digits were before it:
function sanitizeDigitsPreservingCaret(input) {
const { value, selectionStart = value.length } = input;
const digitsBeforeCaret = value.slice(0, selectionStart).replace(/\D+/g, "").length;
const cleaned = value.replace(/\D+/g, "");
if (value === cleaned) return;
input.value = cleaned;
let nextPos = 0;
let seen = 0;
while (nextPos < cleaned.length && seen < digitsBeforeCaret) {
nextPos++;
seen++;
}
input.setSelectionRange(nextPos, nextPos);
}
document.querySelector("#otp-input")?.addEventListener("input", (e) => {
sanitizeDigitsPreservingCaret(e.currentTarget);
});
3. Common Traps to Avoid
- Using
<input type="number">for digit codes or IDs:type="number"allowse/E,+,-, and decimals in many browsers, strips leading zeros (turning"007"into"7"), and can change values on scroll wheel. - Blocking keys only in
keydown: Users can still paste"abc123", drag text, or use IME/autofill—always sanitize oninputand validate on form submission and the server. - Using
\dwhen you only want ASCII0-9: In JavaScript regexes,\dmatches[0-9], whereas\Dmatches anything not in[0-9]; if you want extra clarity or need strict ASCII checks,[0-9]and[^0-9]are unmistakable.
TL;DR: Use <input type="text" inputmode="numeric" pattern="[0-9]*"> to trigger a numeric mobile keypad, sanitize with .replace(/[^0-9]/g, "") on the input event to catch pastes and autofill, and avoid type="number" for codes, PINs, or leading-zero values.
Are you collecting codes/PINs with leading zeros, formatting a phone or card number, or handling decimals and negative numbers?
