You are here:Home»KB»Programming»Javascript»Javascript Input Box Key Restrictors
Saturday, 28 August 2010 00:00

Javascript Input Box Key Restrictors

Written by

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

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

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

Read 2075 times Last modified on Sunday, 10 December 2017 13:24