javascriptdom-eventswhitelistonkeypress

Javascript limit text input characters


I am wanting to restrict the input characters for a text box to [a-z0-9_-]. However whenever if do this buttons like backspace and the arrow keys don't work. I have found some attempts on this website and others but either they don't work properly on all browsers or they use a black list. For example the W3Schools website example black lists numbers. Is there a way to use white list (the one above) and still allow keys like backspace, arrows, home, end etc? Or do I have to add everyone of the key codes that match the keys I want to allow? I do something like this (this is shortened for simplicity).

EDIT - Added code

 <input type="text" onkeypress="return checkInput();">
    function checkInput(){
        return /[a-z0-9_-]/gi.test(String.fromCharCode(window.event.keyCode));
    }

Solution

  • Just change the regex in the example to something like this:

    numcheck = /[^a-z0-9_-]/;
    

    Or better yet, avoid the double negative with:

    numcheck = /[a-z0-9_-]/;
    return numcheck.test(keychar);
    

    Then you can look up the keycodes of backspace, etc. and check for them too:

    if (keychar === 8) return true;
    ...
    

    Or even put them in your regex:

    numcheck = /[a-z0-9_\x08-]/;