Regular expression for password validation
A password validation regex for forms that require uppercase, lowercase, digit and special character rules.
Instead of coding “at least 8 characters, one uppercase letter, one digit and one special character” rule by rule, a single regular expression can do the whole check.
The (?=...) groups are lookaheads: they inspect what follows without consuming it. Four lookaheads check for a lowercase letter, an uppercase letter, a digit and a special character; the trailing {8,} sets the minimum length.
Raise the length to tighten the rule, or drop a lookahead to relax it. Remember that client-side password checking only gives the user fast feedback — the same check must run on the server.
^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,}$
Short guide
When to use it
A password regex can provide a first quality check on signup and password change screens. A good password policy, however, is not only about counting character types; it should guide users clearly.
What to watch
- Show the rule to the user instead of making them guess what is missing.
- Prefer length and resistance to predictable patterns over excessive complexity.
- Never store passwords as plain text; use a secure hash and salt.
Common mistake
An overly strict regex can push users toward weak passwords that merely satisfy the rule. Stronger guidance often works better than more symbols.
Before using this in a project
Regex examples are useful shortcuts, but real projects should also consider the data source, line endings, browser/server differences and user input mistakes. In web forms, admin panels and custom software, validation should not live only on the frontend; the server side should check it too.