Back to roadmaps regex Course

Password Complexity Validation with Regex

Strong password requirements typically mandate that a password must contain uppercase letters, lowercase letters, digits, and special characters, all of a minimum length. Using lookahead assertions, we can validate all these conditions in a single regex.


1. Building the Password Regex

We chain multiple lookahead assertions, each checking for one condition independently:

const strongPasswordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$/;

strongPasswordRegex.test("Passw0rd!");  // true
strongPasswordRegex.test("password1!"); // false (no uppercase)
strongPasswordRegex.test("PASSWORD1!"); // false (no lowercase)
strongPasswordRegex.test("Passw0rd");   // false (no special character)
strongPasswordRegex.test("Pw1!");       // false (too short, under 8 characters)

2. Pattern Breakdown

Component Purpose
^ Assert start of string
(?=.*[a-z]) Must contain at least one lowercase letter
(?=.*[A-Z]) Must contain at least one uppercase letter
(?=.*\d) Must contain at least one digit
(?=.*[!@#$%^&*]) Must contain at least one special character
.{8,} Must be at least 8 characters long
$ Assert end of string

3. Giving Helpful Feedback to Users

Instead of a single pass/fail result, you can run individual checks and provide specific error messages:

function validatePassword(password) {
  const errors = [];
  if (!/[a-z]/.test(password)) errors.push("Must include a lowercase letter.");
  if (!/[A-Z]/.test(password)) errors.push("Must include an uppercase letter.");
  if (!/\d/.test(password)) errors.push("Must include a digit.");
  if (!/[!@#$%^&*]/.test(password)) errors.push("Must include a special character (!@#$%^&*).");
  if (password.length < 8) errors.push("Must be at least 8 characters.");
  return errors;
}
Published on Last updated: