Giraffe
Giraffe

Reputation: 1

Javascript RegExp.test not working

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

Upvotes: 0

Views: 122

Answers (1)

Alan Moore
Alan Moore

Reputation: 75222

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.

Upvotes: 2

Related Questions