Take the 2-minute tour ×

I am trying to validate a password string with javascript and need some help with a regex. I have tried some tutorials, but I think I have some problems understanding how to escape quantifiers and/or metacharacters.

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


The first three spans are pretty easy, but I can't figure out the last one. Basically my script looks something like this:

var password = "user_input_password";

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

Any help or input is highly appreciated, thanks!

share|improve this question

3 Answers 3

up vote 4 down vote accepted

In general, you can escape a meta-character using a backslash \; however, inside a character class, the only ones you have to escape are ] , \ and - (the ^ only has a meaning at the very beginning). Something like [\w!@#%&/(){}[\]=?+*^~\-.:,;] will do what you want.

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

So the full test would be something like:

share|improve this answer
you also need to espace "-" symbol. it defines range inside []. –  Nakul Nov 26 '11 at 8:06
Yeah, you're right. I even noted that in my answer, but left it out of the code. –  Tikhon Jelvis Nov 26 '11 at 8:07
This works great, thank you! –  José Nov 26 '11 at 8:23
share|improve this answer
I don't think you need to escape the [ or . or /. –  Tikhon Jelvis Nov 26 '11 at 8:08

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


To exclude quotes as well (I didn't see them in your example) you can add those in:

share|improve this answer

Your Answer


