In this post, I’ll be showing you two easy ways you can use to restrict an HTML input element to allow only numeric values.
1. Set the input type to “number”:
Inputs of type “number” have built-in validation to reject non-numerical values. The downside is the spin-buttons that appear when hovering over the input box (check the example below)
<input type="number" value='10'>
Try it:
2. The “input” event and regular expression with JavaScript:
If you don’t like the spin-buttons, this is the right way for you.
Note: we are using the input of type text.
<!-- if the input value is not a number, replace it with an empty string -->
<input type="text" value="10" oninput="this.value = this.value.replace(/[^0-9.]/g, '')">
Try it: