Regex for a strong password

This pattern uses lookaheads to require a lowercase letter, an uppercase letter, a digit and a symbol, with at least eight characters. Each lookahead checks one rule without consuming characters.

The pattern

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{8,}$/m

The tester opens with this pattern and the examples below already loaded. Nothing you type is uploaded.

How it works

(?=.*[a-z])
Somewhere ahead there is a lowercase letter.
(?=.*[A-Z])
Somewhere ahead there is an uppercase letter.
(?=.*\d)
Somewhere ahead there is a digit.
(?=.*[^\w\s])
Somewhere ahead there is a symbol (not a letter, digit, underscore or space).
.{8,}
At least eight characters in total.

Examples

Matches

  • Passw0rd!
  • Str0ng#Pass
  • Tr1cky_Mix-9

Does not match

  • password
  • PASSWORD1!
  • Short1!

Use it in JavaScript

const re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{8,}$/m;

// Find every match in a block of text
const found = text.match(re);

// Validate that a whole value matches (no stray characters around it)
const exact = new RegExp('^(?:' + re.source + ')$', re.flags.replace('g', ''));
const isValid = exact.test(value);

Limits and tips

  • The underscore counts as a word character here, so it does not satisfy the symbol rule.
  • Current guidance from standards bodies such as NIST favours length and checking against lists of breached passwords over composition rules, so consider a longer minimum length instead of forcing symbols.
  • Always enforce password rules on the server as well. A client-side regex is only a convenience.

Frequently asked questions

Why use lookaheads for password rules?

Lookaheads let several independent conditions apply to the same string without caring about the order of characters.

How do I require a longer password?

Change the 8 in .{8,} to a larger number, for example .{12,}.