Regular expression for complex password

I need to validate passwords that must comply with the following rules:

  • The minimum length is 8 characters.
  • All symbols must be unique
  • At least one of the characters is uppercase
  • At least one character is a non-alphabetic character, number, or hyphen
  • Non-alphabetic characters must not fit in the first two or the last two characters

I can't figure out how to check this with regular expressions. Can anyone help me?

+3


source to share


2 answers


^(?=.*[A-Z])(?=.*(?:\d|-))(?!.*(.).*\1)[a-zA-Z]{2}.{4,}[a-zA-Z]{2}$

      

Try it. Check out the demo.

https://regex101.com/r/eZ0yP4/12

As you can see step by step, all the conditions are met with the lookahead.



(?=.*[A-Z])

=== at least one Capital

(?=.*(?:\d|-))

=== at least one digit or -

(?!.*(.).*\1)

=== no duplicates

[a-zA-Z]{2}.{4,}[a-zA-Z]{2}

=== alphabetic characters both the first two and the last two.

+5


source


You can use the vt password library . The code is quite long, but it is easy to modify and well supported.



// password must be between 8 and 16 chars long
LengthRule lengthRule = new LengthRule(8, 16);

// don't allow whitespace
WhitespaceRule whitespaceRule = new WhitespaceRule();

// control allowed characters
CharacterCharacteristicsRule charRule = new CharacterCharacteristicsRule();
// require at least 1 digit in passwords
charRule.getRules().add(new DigitCharacterRule(1));
// require at least 1 non-alphanumeric char
charRule.getRules().add(new NonAlphanumericCharacterRule(1));
// require at least 1 upper case char
charRule.getRules().add(new UppercaseCharacterRule(1));
// require at least 1 lower case char
charRule.getRules().add(new LowercaseCharacterRule(1));
// require at least 3 of the previous rules be met
charRule.setNumberOfCharacteristics(3);
// don't allow alphabetical sequences
AlphabeticalSequenceRule alphaSeqRule = new AlphabeticalSequenceRule();

// don't allow numerical sequences of length 3
NumericalSequenceRule numSeqRule = new NumericalSequenceRule(3);

// don't allow qwerty sequences
QwertySequenceRule qwertySeqRule = new QwertySequenceRule();

// don't allow 4 repeat characters
RepeatCharacterRegexRule repeatRule = new RepeatCharacterRegexRule(4);

// group all rules together in a List
List<Rule> ruleList = new ArrayList<Rule>();
ruleList.add(lengthRule);
ruleList.add(whitespaceRule);
ruleList.add(charRule);
ruleList.add(alphaSeqRule);
ruleList.add(numSeqRule);
ruleList.add(qwertySeqRule);
ruleList.add(repeatRule);

PasswordValidator validator = new PasswordValidator(ruleList);
PasswordData passwordData = new PasswordData(new Password("testpassword"));

RuleResult result = validator.validate(passwordData);
if (result.isValid()) {
  System.out.println("Valid password");
} else {
  System.out.println("Invalid password:");
  for (String msg : validator.getMessages(result)) {
    System.out.println(msg);
  }
}

      

+3


source







All Articles