0

I'm trying to write a regular expression for a strong password.

/*  Regular expression explained
o Must contain at least one number: (?=.*\d)
o Must contain at least one letter: (?=.*[a-zA-Z])
o Must contain at least one symbol: (?=.*[!@#$*_=|?{}\[\]~\-,.])
o No whitespace:                        (?=\S+$)
o Length 8 - 25 characters long:        .{8,25}
*/

pass = document.getElementById('password').value;
var PwdRegExpStr = "^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$*_=|?{}\[\]~\-,.])(?=\S+$).{8,25}$"
var PwdRegExp = new RegExp(PwdRegExpStr);
var PwdRegExpStr2 = "^.*(?=.{8,25})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$?]).*$"
var PwdRegExp2 = new RegExp(PwdRegExpStr2);

var patt =  /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$*_=|?{}\[\]~\-,.])(?=\S+$).{8,25}$/
var patt2 = /^.*(?=.{8,25})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$/
alert("Pass:"+pass+" = "+PwdRegExp.test(pass)+" = "+PwdRegExp2.test(pass)+" = "+patt.test(pass)+" = "+patt2.test(pass));

I'm seeing the following results when i enter "qwer1234$": Pass:qwer1234$ = false = false = true = true

Can you help me understand why they're not all evaluating true?

Thanks

3
  • Perhaps it's trying to suggest that don't validate passwords using regex? Commented Apr 11, 2014 at 18:06
  • That's weird, I'm kind of stumped. Either way, you should create expressions literally (/^abc$/.test('abc')) in JavaScript if you can. And that's the one that returns true. Commented Apr 11, 2014 at 18:11
  • Thanks Sam, I'm actually passing into the javascript the minimum password length from configuration. That's why I was hoping to use the RegExp version to concatenate it into the string prior to defining the regular expression. Commented Apr 11, 2014 at 18:19

1 Answer 1

2

Your main problem is bad escaping. When you specify the regex in the form of a string literal, you have to escape the backslashes. So this:

"^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$*_=|?{}\[\]~\-,.])(?=\S+$).{8,25}$"

...should be:

"^(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!@#$*_=|?{}\\[\\]~\\-,.])(?=\\S+$).{8,25}$"

On a side note, I don't see any need to write (?=\S+$).{8,25}$ when \S{8,25}$ will do. And in your other version, the extra .* after the ^ makes no sense. It still works, but you're making the regex engine do a lot more work than it should.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.