0

I am writing a javascript regex for the following:

  1. must have at least one digit
  2. must have at least one capital letter
  3. must be between 8-15 characters

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.

2 Answers 2

1

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: .*?.

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

2 Comments

sir, the regex you have given works very well. I didnt get why in my case I had to give 7,14 but in your regex you did the length checking with 8,15 ?
Because in your expression, (^[A-Za-z0-9]) already matched and consumed a character, so there would be only 7 to 14 let to match. In my expression, there are only lookaheads, which don't consume any characters, so the . has to match 8 to 15 times.
1

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
/              

4 Comments

I have not tried yet your answer. But my regex does match with 1Aaaaaaa , aaaaaaA1, 111Aaaa etc... I think it is not the reason.
The reason is, that it specifies a letter or number to start the regex, and then afterwards, to have a capital letter. So it does not match your test, which only has a capital at the beginning, and not after that.
oh yes, now I get your point. thanks so much for the explanation. regex is my weak side :)
regex is a dark art, usually problematic, always under-commented, occasionally indispensable.

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.