javascript limit text input characters

前端 未结 5 1265
攒了一身酷
攒了一身酷 2020-12-22 06:30

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 s

5条回答
  •  无人及你
    2020-12-22 07:16

    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-]/;
    

提交回复
热议问题