To restrict input in an HTML <input>
field to allow only digits (0 and positive numbers), you can use several approaches.
1. Using the type="number"
Attribute
HTML provides a built-in type for numbers:
<input type="number" min="0" oninput="validity.valid || (value='');" />
- The
min="0"
attribute prevents negative numbers from being entered. - The
oninput
event resets the field if invalid characters (e.g., letters) are entered.
Drawback: Users can bypass this restriction using developer tools.
2. Adding a Restriction Using pattern
(Regular Expression)
You can use the pattern
attribute:
<input type="text" pattern="^[0-9]*$" title="Enter only a positive number or 0" />
pattern="^[0-9]*$"
allows only digits (0–9).- The
title
attribute provides a hint if the user enters invalid characters.
3. JavaScript for Dynamic Validation
If stricter control is needed (e.g., to prevent typing invalid characters), use JavaScript:
<input type="text" id="numberInput" />
<script>
const input = document.getElementById('numberInput');
input.addEventListener('input', () => {
input.value = input.value.replace(/[^0-9]/g, ''); // Removes everything except digits
});
</script>
4. Combining Methods
You can combine the above methods for enhanced restriction:
<input
type="text"
pattern="^[0-9]*$"
title="Enter only a positive number or 0"
oninput="this.value = this.value.replace(/[^0-9]/g, '');"
/>
The most versatile and reliable approach is to combine the pattern
or type="number"
attributes with JavaScript for dynamic input handling.