Last active
March 11, 2023 11:37
-
-
Save phegman/755bd41197cd59c435db56c367d9d0fd to your computer and use it in GitHub Desktop.
Prevent non-numeric values in number input with JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input | |
type="number" | |
id="number-input" | |
step="any" | |
pattern="[0-9\.\-]*" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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