How To Only Allow Alpha Numeric Chars With JavaScript

前端 未结 3 1395
花落未央
花落未央 2020-12-01 23:40

Been playing around with JavaScript, and what Im trying to do is only allow certain characters in the pass word field - a-z, A-Z and 0-9.

3条回答
  •  鱼传尺愫
    2020-12-02 00:22

    You need to make your condition test a regexp, not a string:

    if(!/^[a-zA-Z0-9]+$/.test(name)){ ...
    

    meaning:

    • ^ -- start of line
    • [a-zA-Z0-9]+ -- one or more characters/numbers
    • $ -- end of line

    or you could search for the inverse of that, which is "any non-accepted character":

    if(/[^a-zA-Z0-9]/.test(name)){
    

提交回复
热议问题