Javascript regex validates password string (avoiding punctuation)

I am trying to check the password string using javascript and you need help with regex. I tried some tutorials, but I think I have some problems understanding how to avoid quantifiers and / or metacharacters.

I want to make sure that the password string contains only one or more characters (maximum 32) from the following intervals:

"abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "012345678901234567890123456789" " !@ #%&/(){}[]=?+*^~-_.:,;" 

The first three flights are quite easy, but I can not understand the last. Basically my script looks something like this:

 var password = "user_input_password"; if (/^[ A-Za-z0-9!@ #$%...]{1,32}$/.test(password)) { document.write('OK'); } else { document.write('Not OK'); } 

Any help or input is appreciated, thanks!

+4
source share
3 answers

In general, you can escape the metacharacter with the backslash \ ; however, within the character class, the only ones you need to escape with are ] , \ and - (the value ^ only makes sense at the very beginning). Something like [\ w!@ #%&/(){}[\]=?+*^~\-.:,;] Will do what you want.

\w is [A-Za-z0-9_] .

So a complete test would be something like this:

 /^[\ w!@ #%&/(){}[\]=?+*^~\-.:,;]{1,32}$/.test(password) 
+4
source
 /^[ A-Za-z0-9!@ #%&\/(){}\[\]=?+*^~\-_\.:,;]{1,32}$/ 
+2
source

You can also match all characters that are not considered spaces (space, newline, tab)

 /^[^\s]{1,32}$/.test(password); 

To exclude quotes (I did not see them in your example), you can add them to:

 /^[^\s'"]{1,32}$/.test(password); 
0
source

Source: https://habr.com/ru/post/1383164/


All Articles