How do I check if the key pressed on a form field is a digit (0 - 9)?
See these:
- HTML Text Input allow only Numeric input
- allow digits only for inputs
Use event.key
to get the actual value. To check if integer, just use isFinite
input.addEventListener("keydown", function(event) {
const isNumber = isFinite(event.key);
});
Other option:
const isNumber = /^[0-9]$/i.test(event.key)
An easier HTML solution would be to use the number
type input. It restricts to only numbers (kind of).
<input type="number">
Either way, you should clean all user input with:
string.replace(/[^0-9]/g,'');