Password Validation with Regex (and When Not To)
Published · 5 min read
Search for "password regex" and you will find dozens of near-identical one-liners demanding an uppercase letter, a lowercase letter, a digit and a symbol. They work, in the sense that they do what they say. Whether you should use one is a separate question. This article covers both: how the classic lookahead pattern is built, what current guidance says about composition rules, and how to implement the checks cleanly in languages whose regex engines have no lookahead at all.
What current guidance actually recommends
The most widely cited reference is NIST Special Publication 800-63B, the US digital identity guidelines that cover passwords (which NIST calls memorized secrets). Its direction has been consistent for several revisions now, and it moved away from the rules many sites still enforce. In short, it favours:
- A minimum length, with longer minimums when the password is the only factor protecting the account.
- Accepting long passwords. Verifiers should allow at least 64 characters, so passphrases fit.
- Accepting spaces and any printable characters, including Unicode.
- Checking new passwords against a blocklist of values that are commonly used, expected, or known to have been compromised.
- Not imposing composition rules such as "must contain a digit and a symbol", and not forcing periodic password changes without evidence of compromise.
The reasoning is practical. Composition rules push people towards predictable patterns, such as a capital first letter and 1! on the end, which attackers already try first. Length adds far more guessing work, and a blocklist catches the truly weak choices that composition rules let through, like Password1!.
A length-only pattern
If length is the rule, the regex is tiny. This accepts 12 to 64 characters of anything except a line break:
^.{12,64}$Honestly, you rarely need a regex here at all: password.length >= 12 is clearer. One subtlety is worth knowing. In JavaScript, .length and . without the u flag count UTF-16 code units, so an emoji counts as two characters. Use the u flag, or count with [...password].length, if you want characters as people see them. The unicode text lesson explains why.
The classic lookahead pattern
When a policy does require character classes, the standard regex approach uses lookaheads. A lookahead, written (?=...), checks that something can be matched from the current position without consuming any characters. Stack several at the start of the string and each one tests an independent rule:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{12,64}$How it reads
^anchors at the start of the input.(?=.*[a-z])looks ahead for at least one lowercase letter anywhere.(?=.*[A-Z])does the same for an uppercase letter, and(?=.*\d)for a digit.(?=.*[^A-Za-z0-9])requires one character that is not an ASCII letter or digit, which covers symbols and spaces..{12,64}$finally consumes the whole input and enforces the length.
Because every lookahead starts from the same position, the order of the rules does not matter. Adding or removing a rule is a matter of adding or deleting one group. The lookahead lesson has interactive exercises, and a tested version of this pattern lives in the library as strong password.
Using it in JavaScript
const STRONG = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{12,64}$/;
STRONG.test("Correct-Horse-42"); // true
STRONG.test("correct-horse-42"); // false: no uppercase letter
STRONG.test("Short-1a"); // false: too shortThe weakness of a single pattern
A single regex answers yes or no. It cannot tell the user which rule failed, so the form ends up showing a vague "password does not meet requirements" message. That alone is a good reason to split the rules up, even in languages that support lookahead.
Checking rules separately
Testing each rule on its own is easier to read, easier to change, and gives precise feedback. Here is the same policy in Python, returning a list of problems:
import re
RULES = [
(re.compile(r"[a-z]"), "add a lowercase letter"),
(re.compile(r"[A-Z]"), "add an uppercase letter"),
(re.compile(r"[0-9]"), "add a digit"),
(re.compile(r"[^A-Za-z0-9]"), "add a symbol or space"),
]
def password_problems(pw: str) -> list[str]:
problems = []
if not 12 <= len(pw) <= 64:
problems.append("use 12 to 64 characters")
for pattern, message in RULES:
if not pattern.search(pw):
problems.append(message)
return problems
print(password_problems("Correct-Horse-42")) # []Note the use of search rather than match or fullmatch: each rule only needs to be found somewhere in the password.
Go and Rust have no lookahead
Go's standard regexp package and Rust's regex crate are built for guaranteed linear-time matching, and they deliberately leave out lookaround and backreferences. Paste the lookahead pattern into either and it fails to compile. The fix is the same split shown above: one simple pattern per rule, or no regex at all.
import (
"regexp"
"unicode/utf8"
)
var (
lower = regexp.MustCompile("[a-z]")
upper = regexp.MustCompile("[A-Z]")
digit = regexp.MustCompile("[0-9]")
other = regexp.MustCompile("[^A-Za-z0-9]")
)
func strongEnough(pw string) bool {
n := utf8.RuneCountInString(pw)
return n >= 12 && n <= 64 &&
lower.MatchString(pw) && upper.MatchString(pw) &&
digit.MatchString(pw) && other.MatchString(pw)
}Rust looks almost identical with Regex::new and is_match. For more on which features each engine supports, see regex differences between languages.
Adding a blocklist
A blocklist is not a regex problem. It is a set lookup, usually against a list of common and breached passwords that you ship with the application or check through a privacy-preserving service. Normalise before comparing so trivial variations do not slip through:
const BLOCKED = new Set(["password", "password1", "qwertyuiop", "123456789012"]);
function isBlocked(pw) {
return BLOCKED.has(pw.trim().toLowerCase());
}In a real application the list would hold many thousands of entries. The principle is the same: reject the passwords attackers try first, regardless of how many character classes they contain.
Where regex still earns its place
None of this means regex has no role in password handling. It is simply better suited to narrow, well-defined checks than to judging strength. A few cases where a pattern is the right tool:
- Numeric PINs with a fixed length, such as
^\d{6}$for a six-digit code. Here the shape really is the whole rule. - Rejecting a password made of one repeated character, for example
^(.)\1+$, which matchesaaaaaaaaaaaaand111111111111. - Spotting obvious sequences such as
0123456789orabcdefghbefore the blocklist lookup, if your list does not already contain them. - Checking that generated secrets, like API keys or one-time tokens, have the exact format your system issues.
A related check that is better done without regex: making sure the password does not contain the user's own email address or username. Lower-case both values and use a plain substring test such as includes. Building a regex from user input would require escaping every special character first, which adds risk for no benefit.
Whichever rules you keep, show them before the user starts typing, then tick each one off as it is met. People should never have to guess a policy from a series of rejections.
Pitfalls to avoid
- Low maximum lengths. Capping passwords at 16 or 20 characters blocks passphrases and password managers. Allow at least 64.
- Rejecting spaces or Unicode. A character class like
[A-Za-z0-9!@#$%]quietly forbids everything else. Prefer negated sets such as[^A-Za-z0-9]when you need "any symbol". - Trimming or altering the password before hashing. Whatever the user typed is the secret; changing it can lock them out later.
- Validating only in the browser. Client-side checks are for feedback. Repeat the rules on the server.
- Unbounded patterns on long input. Keep the length limit in place; it protects against slow matching, covered in the ReDoS lesson.
Want to try the patterns from this post? Paste them into the RegexLab tester with a few sample passwords on separate lines and the multiline flag turned on. Everything runs locally in your browser, but use made-up passwords anyway: real ones do not belong in any test tool.
Frequently asked questions
- What is a good regex for a strong password?
- A common pattern is ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{12,64}$, which requires lowercase, uppercase, a digit, a symbol and 12 to 64 characters. Current guidance favours length and blocklists over these composition rules.
- Does NIST recommend password composition rules?
- No. NIST SP 800-63B advises against composition rules and forced periodic changes, and instead recommends minimum length, support for long passwords, and screening against lists of common or compromised passwords.
- How do I validate a password in Go or Rust without lookahead?
- Compile one simple pattern per rule, such as [a-z] or [0-9], and require each to match, plus a separate length check. This also lets you report exactly which rule failed.
- Should password validation happen on the client or the server?
- Both. Client-side checks give quick feedback while typing, but the server must enforce the same rules because client code can be bypassed.
Related posts
- Regex for Beginners: A Practical IntroductionLearn regex from scratch: literals, character sets, quantifiers, anchors, groups and flags, with small tested examples in JavaScript and Python.
- CNIC Validation with Regex: Checking the FormatCheck the shape of a Pakistani CNIC number (12345-1234567-1) with regex in JavaScript and Python, and learn what a format check can and cannot prove.
- Regex vs AI: When to Use WhichRegex vs AI for text tasks: determinism, cost, privacy and speed versus flexibility, and how to combine the two safely in real projects.