0

I am trying to validate password using regex .my condition is that Password should have

  1. One special character
  2. One number
  3. One lower case
  4. One upper case
  5. minimum 8 characters

Below is my code snippet

var a = "Test@123"
if (/^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[@$!%?&])[A-Za-z\d@$!%?&]{8,}$/.test(a)) {
  console.log('=====true')
} else {
  console.log('false')
}

it should show true on console. but currently it is showing false why ?

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
user944513
  • 12,247
  • 49
  • 168
  • 318

1 Answers1

2

You missed quantifiers in positive lookahead, currently

   (?=.[a-z])

Here . means match anything except new line since no quantifier so it will match only one time, [a-z] means match lowercase alphabet once, so your all positive lookaheads are looking for values at index 1 which can never satisfy all the positive lookaheads conditions as we are looking for different different values in each positive lookahead,

So when we use (?=.*[a-z]) quantifier which means match anything zero or more time and then should be followed by lowercase alphabet, so it makes the values before condition dynamic

var a = "Test@123"
if (/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%?&])[A-Za-z\d@$!%?&]{8,}$/.test(a)) {
  console.log('=====true')
} else {

  console.log('false')
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60