Password check with combined regexes

Viewed 61

In Laravel, I have to do a strong security check for passwords. I don't have any prior knowledge of Regex, but I think it is the best solution in my case and I believe it can do what I need. So here are my client's rules:

A password must contain all 4 characters’ types:

  • Lowercase : a-z
  • Uppercase : A-Z
  • Numeric : 0-9
  • Special characters: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
  • Your user name, first name or last name should not be part of your password.
  • Consecutive set of the same character should never be used (aaaaaa..., 1111111...)

Searching through Stackoverflow, I found a similar solution which deals with first 4 rules, but with my necessary modifications:

/^.*(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!"#$%&'()*+,-.\/:;<=>?@[\]^_`{|}~]).*$/

Also, I found a solution for the last rule (consecutive set of characters - 6 in this case), which should probably be a little bit more modified, because I actually don't want a password to have a repeating set of characters. It searches for repeating set:

/(.)\1{5,}/

About the "names can't be part of the password" rule, is it even possible to do it within regex, since we have to pass a string parameter(s) to it?

Anyway, I would like to have 1 regex for all rules combined. Since that probably isn't doable, is it possible to have at least a combined regex for everything except the part about "no usernames allowed"? And then I could do a custom validation for that specific rule.

I don't think that my question is duplicate, since it's a combination of at least 2 questions together. Given "duplicate" is just a part of my regex, which I didn't know how to combine with the other one.

1 Answers

One option is to add a negative lookahead which asserts that nowhere in the entered password do two consecutive characters appear:

/^(?!.*(.)\1)(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!"#$%&'()*+,-.\/:;<=>?@[\]^_`{|}~]).*$/
   ^^^^^^^

Note that the .* you had at the beginning of your pattern was probably misplaced. You don't need/want it there, because you want the lookaheads to fire before you begin matching the actual password.

Demo

Related