Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Created May 16, 2022 20:41
Show Gist options
  • Save allenhwkim/91ee0d053b8f01b9811691f844e07d65 to your computer and use it in GitHub Desktop.
Save allenhwkim/91ee0d053b8f01b9811691f844e07d65 to your computer and use it in GitHub Desktop.
restrict Keyboard Input
$('#my-input').addEventListener('keydown', restrictKeyboardInput);
$('#my-input').addEventListener('paste', restrictKeyboardInput);
function restrictKeyboardInput(event) {
if (event.type === 'keydown' && !event.key.match(/^[a-zA-Z0-9-_\ .]$/)) {
if (event.keyCode === 8 || event.keyCode === 46 || event.keyCode === 9) {
// Allow backspace, delete and Tab key
} else if (event.keyCode >= 37 && event.keyCode <= 40) {
// Allow left, right, up and down arrows
} else {
console.error('keyboard input not allowed', event.key);
event.preventDefault();
return false;
}
} else if (event.type === 'paste') {
const text = (event.originalEvent || event).clipboardData.getData('text/plain');
if (!text.match(/^[a-zA-Z0-9-_\ .]+$/)) {
console.error('paste not allowed', text);
event.preventDefault();
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment