1

I need help with a RegEx for a password. The password must contain at least one special char (like "§$&/!) AND a number.

E.g. a password like "EdfA433&" must be valid whereas "aASEas§ö" not as it contains not a number.

I have the following RegEx so far:

^(?=.*[0-9])(?=.*[a-zA-Z]).{3,}$ 

But this one is obviously checking only for a number. Can anyone help?

3 Answers 3

2

You're better off just using multiple more simple regular expressions: any code checking anything like this won't be performance sensitive, and the additional complexity of maintenance given a more complex regexp probably isn't justifiable.

So, what I'd go for:

var valid = foo.match(/[0-9]/) && foo.match(/["§$&/!]/); 

I wonder if you really want to define special characters like that: Does é count as a special character? Does ~ count as a special character?

Sign up to request clarification or add additional context in comments.

2 Comments

The chars above were only examples - everything else than [a-zA-Z0-9] counts as special character. Maybe it's really a good idea to split this into two separate expressions.
This probably is the most simple solution. I now used: val.match(/[0-9]/) && val.match(/\W/);
2
 ^(?=.*\d)(?=.*\W).{3,}$ 

checks for at least one digit (\d) and one non-alphanumeric character (\W). \W is the inverse of \w which matches digits, letters and the underscore.

If you want to include the underscore in the list of "special characters", use

 ^(?=.*\d)(?=.*[\W_]).{3,}$ 

2 Comments

Thanks! Though it seems the underscore won't work at the beginning of the string.
I'm giving gsnedders the accepted answer as he was a little bit faster. Both answers solved my problem well. Thanks!
1

I would divide function that checks if password is "hard" into some parts and in each part I would check one condition. You can see some complicated regex on Daily WTF with password reset: http://thedailywtf.com/Articles/The-Password-Reset-Facade.aspx

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.