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)){ ...
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)){
if (name.match(/[\W_]/)) { //...
Meaning if the "name" string has any character which is a non-alphanumeric or an underscore then execute the block. Note that we have to separately check for underscore (_
) because the alphanumeric character class (\w
) includes the underscore (so the negative class (\W
) does not).