1

I have seen answers for strong password checks but I have an additional requirement for the order in which the characters appear.

The password should contain at least:

  1. One upper case letter.
  2. One lower case letter.
  3. One number.
  4. One special character.

The order being:

  • Should start with upper case and lower case letters.
  • Followed by number and/or alphabetical characters.
  • In the end, should be a special character.

e.g.

  • Xyz1325@ is valid.
  • aBcd123xYz# is also valid.
  • @Xyz1234 is invalid.
  • 1234Xyz@ is invalid.
  • Xyz@ is invalid.
James Z
  • 12,209
  • 10
  • 24
  • 44

2 Answers2

1

The regex I believe you are looking for is this: https://regex101.com/r/nO2DxE/2

Explanation: These groups (?=.*[A-Z].*) (?=.*[0-9].*) (?=.*[a-z].*) make sure your string contains at least one uppercase letter, one lowercase letter and one digit. The rest of the regex checks that the order you described is respected.

Overall, the regex is: (?=.*[A-Z].*)(?=.*[0-9].*)(?=.*[a-z].*)^[a-zA-z][a-zA-Z0-9]*[@!#+-]$

1

Introducing a specific order of characters in a password makes it relatively more predictable, hence losing the strength of it, and I'll suggest you to get away with that restriction. Nevertheless, you can use this regex that will meet your needs,

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[~!@#$%^&*])[a-zA-Z][a-zA-Z\d]*[~!@#$%^&*?<>]*$

Explanation:

  • ^ --> Start of string
  • (?=.*[a-z]) --> Ensures the password has at least one lowercase letter.
  • (?=.*[A-Z]) --> Ensures the password has at least one uppercase letter.
  • (?=.*\d) --> Ensures the password has at least one digit.
  • (?=.*[~!@#$%^&*]) --> Ensures the password has at least one special character from this set. You can put more characters inside that you want to treat as special.

Now comes the part for ensuring the order. As you said it should start with an alphabet, hence we need the first character as,

[a-zA-Z]

Then following it can be alphabet or numbers hence you can use,

[a-zA-Z\d]*

And finally you want special characters, and by your this statement "In the end, should be a special character." I assume you do not want to restrict it to just one single special character, hence at the end of regex it should be this,

[~!@#$%^&*?<>]*

which can match one or more special characters. If you really meant just one special character then just make it [~!@#$%^&*?<>]

And finally end it with $ to stop matching the string.

Live Demo

Hope this works for you. Or else, let me know for any other queries.

Edit

Bonus: If you want to check length as well you can do so using the following:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[~!@#$%^&*])(?=.{6,18}$)[a-zA-Z][a-zA-Z\d]*[~!@#$%^&*?<>]*$

The additional (?=.{6,18}$) is to ensure that your regex has length between 6 to 18.

@Pushpesh, Please correct if wrong.

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36