Created
May 16, 2022 20:41
-
-
Save allenhwkim/91ee0d053b8f01b9811691f844e07d65 to your computer and use it in GitHub Desktop.
restrict Keyboard Input
This file contains hidden or 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
| $('#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