Home > Software engineering >  Regex problem for password strength check
Regex problem for password strength check

Time:09-27

I'm making a password checker that requires at least one of a-z, A-Z, 0-9, and #?!@$%^&* -_ each. I made a rule but it shows false-positive. I don't know what's wrong with my rule. Thanks,

const re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[#?!@$%^&* -_]).{8,}$/
re.test('Abcde0927')  // This should be false. Why true?

CodePudding user response:

There is a problem in your one condition (?=.*[#?!@$%^&* -_]). You have written -_ which essentially means any character from to _ in the ascii table, and NOT JUST to include these three -_ characters literally.

You should always be careful while placing hyphen - within square brackets and make sure hyphen is either first or last character in that character set else its meaning will change like it did here.

Just change your character set from [#?!@$%^&* -_] to [#?!@$%^&* _-] and it works as you intended.

const re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[#?!@$%^&* _-]).{8,}$/
console.log(re.test('Abcde0927')) // prints false

CodePudding user response:

fixed by escaping some characters

re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[#\?!@\$%\^&\*\ \-_]).{8,}$/
  • Related