Programmable Key Restrictor
This script blocks the input of characters by using a Javascript function attached an input box which is called with the event onkeydown="" . This allows me to prevent input issues with end users because they cannot enter the wrong charcters in the first place. This script is standalone but works well with HTML5 input box validation rules.
I wrote this after I could not get any scripts I found online to work reliable across browsers. I also wanted to be able to make it programmable to account for different types of key restriction I wanted to do. I have use the onkeydown="" event because I believe the the onkeypress="" event only handles printable characters.
The following validators are basically the same with different options and can be programmed for any type of character validation you want including special characters. This script is using the new standard of event.key which with a few tweaks is usable across all of the different browsers. event.key outputs the character that is pressed on the keyboard and not some charcode which varies from browser to browser and platform to platform. event.key is the recommended way of getting key presses in browsers.
As you can see I have used feeder functions to supply the event, you do not need to use them you can create your own and the process is very straight forward. Allowed Characters and whether space is allowed. This prevents a lot of duplicate code as the common function is quite long. You could use the function as a stndalone is you remove the feeder functions and replace them with variables as needed.
Function Call in HTML
<input class="olotd5" value="123456" name="zip" type="text" onkeydown="return onlyAlphaNumeric(event);"/>
The Script
/** Key Input Restrictions - Using event.key **/ // Allows Only Letters function onlyAlpha(e) { return keyRestriction(e, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", true); } // Allow Only Numbers and Letters function onlyAlphaNumeric(e) { return keyRestriction(e, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", true); } // Allow Only Numbers and Letters - Including Comma, Backslash, Minus, Single Quote function onlyAlphaNumericExtra(e) { return keyRestriction(e, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,/-'", true); } // Allows Only Numbers function onlyNumbers(e) { return keyRestriction(e, "0123456789", false); } // Allows Only Numbers and Period function onlyNumbersPeriod(e) { return keyRestriction(e, "0123456789.", false); } // Allow Only Phone Numbers - Including Period, Brackets, Plus, Minus function onlyPhoneNumber(e) { return keyRestriction(e, "0123456789.()-+", true); } // Allow Only valid characters for URL function onlyURL(e) { return keyRestriction(e, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~:/?#[]@!$&'()*+,;=`%", false); } // Allow Only valid characters for Email function onlyEmail(e) { return keyRestriction(e, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@", false); } // Common Function for Key Input Restriction function keyRestriction(e, allowedCharacters, spacesAllowed) { // Grab the character from the pressed key var key = e.key; // Are Spaces Allowed? if (key === ' ' && spacesAllowed === true) return true; // Are Spaces Allowed (IE fix) if (key === 'Spacebar' && spacesAllowed === true) return true; // Control Keys (Backspace, End, Home, Left Arrow, Up Arrow, Right Arrow, Down Arrow, Delete) if (key === 'Backspace' || key === 'End' || key === 'Home' || key === 'ArrowLeft' || key === 'ArrowUp' || key === 'ArrowRight' || key === 'ArrowDown' || key === 'Delete') return true; // Control Keys (IE and Edge fix) if (key === 'Left' || key === 'Up' || key === 'Right' || key === 'Down' || key === 'Del') return true; // Allowed Characters else if (allowedCharacters.indexOf(key) > -1) return true; else return false; }
Notes
- Control Keys - This is where you can allow keys by using charCodes. This is ideal for special keys and non-printable characters like delete.
- Allowed Characters - Add any characters you want to be allowed into the group. It is case sensitive.
Tools
- Javascript Char Codes (Key Codes) - Cambia Research - This tool allows you to press a button and get the charCode of that key. There is also a list of charCodes
- KeyboardEvent Value (keyCodes, metaKey, etc) | CSS-Tricks - A list of charCodes and a link to a tool for getting charCodes. The tool is special key aware i.e. presing a key with Alt or Shift.
- Pen event.keyCode tester - by Chris Coyier (@chriscoyier) on CodePen. - This tester is modifier key aware i.e. Shift and Alt keys.
- Keyboard Event Viewer - Gary Kačmarčík has put together a fantastic demo for visualizing all the attributes associated with KeyboardEvents: Load your browser of choices and press some buttons. All the corresponding events will be shown in a chart as they happen. This is great for seeing browser incompatibilities or differences so you can fix your scripts.
Libraries
- hotkeys - A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.
- keysight | GitHub - A translator for javascript keyboard events to and from consistent and familiar character and key representations. Take your keydown, keypress, and keyup events and reliably translate them into keyboard keys and characters. Its lightweight at 1.06KB minified and gzipped.
onkeypress vs onkeydown vs onkeyup
These javascript events have different roles and can have different outcomes with different browsers. In newer browsers the behavious seems a lot more standard.
- onlyAlphaNumeric() does not work in Firefox so you have to use onlyAlphaNumeric(event)
- onkeypress="" is case sensitive
- causes a lot of special Keys to return a value of 0. This is very flacky and a known bug.
- onkeydown="" is case insensitive
- onKeydown="" has information about the TshiftState and OnKeyPress doesn't, Whether I want to take action for example, if the A key is pressed, depends on whether ssCtrl or ssAlt are combined with it,
- These codes are used to try and get scripts cross browser compliant.
- var key = e.which || e.keyCode; // Use either which or keyCode, depending on browser support
- var charCode = (evt.charCode) ? evt.which : event.keyCode
The notes sayYou should change e.keyCode to e.charCode. --> String.fromCharCode(e.charCode) , I have not verified this. - var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
- KeyCode is 0 - This is caused by browser incompatibility with that particular function. It is also caused by a not printable character being called via onkeypress
- KeyBoardEvents.key - seems to be the same as event.key
- Mottie (CSS-TRICKS) says The charCode, keyCode and which are being deprecated. They will soon be replaced by event.key which will return named keys. This post inspired me to write my script using event.key
- keypress (CSS-TRICKS) does not contain values for special characters. This might of changed in newer browsers but could still be true.
- This fixed a big problem - I changed all onkeypress to onkeydown and this caused Google Chrome to work. This implies a bug if you have both onkeypress and onkeydown events on a page. Quirk? This fixed event.key, so do not use these on the same page. This fixes the issue for both chrome and firefox.
- To get the event passed properly in FireFox you must pass with the function triggered in the HTML by using the varible 'event' giving onlyAlphaNumeric(event) otherwise the script will only work in Chrome.
Links
- What’s New with KeyboardEvents? Keys and Codes! | Web | Google Developers - A well written article on this subject. It also includes references to the execellent tool 'Keyboard Event Viewer'
- KeyboardEvent keyCode Property - A simple description from w3schools including referencing cross browser support code
- UI Events | W3C Working Draft - This draft explains various javascript functions and their upcoming changes but in particular it says "The keydown and keyup events are traditionally associated with detecting any key, not just those which produce a character value."
- Converting keystrokes gathered by onkeydown into characters in JavaScript - Stack Overflow - A nice description about keypress, keydown, keyup events.
- KeyboardEvent.key - Web APIs | MDN - The information sheet from Mozilla on the function KeyboardEvent.key
- Key Values - Web APIs | MDN - The text values for KeyBoardEvents.key
- onKeyPress vs OnKeyDown vs OnKeyUp | The ASP.NET Forums - A very clear table of the differences between the events and what you should use them for.
- javascript - onKeyPress Vs. onKeyUp and onKeyDown - Stack Overflow - A discussion on the subject.
- KeyboardEvent.keyCode - Web APIs | MDN - this information page from mozilla tells you that the function .keyCode is deprecated and that this function should not use this when handling printable cahracters using keydown or keyup.
Legacy Key Restrictors
These are some basic key restrictors that some people use but they are not very cross browser compatible. According to Mottie (CSS-TRICKS) e.which and e.keycode are getting discontinued. I have included these here for reference to see how it was done in the past.
Function Call in HTML
<input class="olotd5" value="123456" name="zip" type="text" onkeydown="return onlyAlphaNumeric(event);"/>
Allows Only Uppercase and Lowercase Letters to be entered - Including Space
// Allows Only Uppercase and Lowercase Letters to be entered - Including Space function onlyAlpha(e) { var charCode = e.which || e.keyCode; if ((charCode === 32 || charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)){ return true; } return false; }
Allows Only Numbers to be entered - Including Backspace and some other keys
// Allows Only Numbers to be entered - Including Backspace and some other keys function onlyNumbers(e) { var charCode = e.which || e.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)){ return false; } return true; }
Links