How To Only Allow Alpha Numeric Chars With JavaScript

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

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


  • ^ — 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”:


Leave a Comment