Reputation: 3424
I am writing a javascript regex for the following:
I have tried it like this:
function isStrongPassword(strInput) {
//works well except A1aaaaaa
var regex = /^(?=.*\d)(^[A-Za-z0-9])(?=.*[A-Z]).{7,14}$/;
return regex.test(strInput);
}
This is working properly, except the fact it is not matching with A1aaaaaa
, which is a valid input.
Any help is appreciated.
Upvotes: 0
Views: 109
Reputation: 58619
Your regex was breaking because of the (^[A-Za-z0-9])
part, which would mean that after a digit, there must be a letter or digit, and then a capital letter. This should work
/^(?=.*\d)(?=.*[A-Z]).{8,15}$/;
Which breaks down like this...
/
^ # start match
(?=.*\d) # is there a digit up ahead (maybe after zero or more anythings)
(?=.*[A-Z]) # is there a capital up ahead (maybe after zero or more anythings)
.{8,15} # 8 to 15 anythings
$ # end match
/
Upvotes: 1
Reputation: 817128
Your expression fails because of (?=.*[A-Z])
. None of the characters following the first one is upper case.
It seems this expression should suffice:
^(?=[^\d]*\d)(?=[^A-Z]*[A-Z]).{8,15}$
Note that switching .*
to [^...]*
has nothing to do with your problem, but it avoids backtracking. Alternatively you could use lazy matching: .*?
.
Upvotes: 1