Skip to content

Instantly share code, notes, and snippets.

@phegman
Last active March 11, 2023 11:37
Show Gist options
  • Save phegman/755bd41197cd59c435db56c367d9d0fd to your computer and use it in GitHub Desktop.
Save phegman/755bd41197cd59c435db56c367d9d0fd to your computer and use it in GitHub Desktop.
Prevent non-numeric values in number input with JavaScript
<input
type="number"
id="number-input"
step="any"
pattern="[0-9\.\-]*" />
/**
* Prevent user from typing non-numeric values in number input
* IMPORTANT: This is only a client-side solution, you should still be
* performing back-end validation!
*/
document.getElementById('number-input').addEventListener(event => {
// Allow keyboard shortcuts
if (
event.getModifierState('Meta') ||
event.getModifierState('Control') ||
event.getModifierState('Alt')
) {
return
}
// Allow non-printable keys
if (key.length !== 1 || key === '\x00') {
return
}
// Prevent any non-numeric keys, but allow . for decimals
// and - for negative values
if ((key < '0' || key > '9') && key !== '.' && key !== '-') {
event.preventDefault()
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment