If your sign-up form rejects long passphrases but accepts Password1!, its password validation in Python needs a fix.
The usual fix, one regex demanding mixed character types, checks the wrong things. It gives no reason and rewards short, predictable passwords.
Quick answer: write a function that returns what’s wrong, and put length and a common-password list ahead of character rules:
if pw.lower() in COMMON or len(pw) < 15:
print("Rejected")
In this tutorial, I’ll cover password validation in Python with string methods, a regex and the NIST length-first rules, then build a getpass checker and hash the result.
It’s all standard library on Python 3.12.5; each VS Code screenshot is a real run.
Password Validation in Python Without Regex
These five demo strings come from the portal’s QA sheet. Don’t reuse them as real passwords:
PASSWORDS = [
"abc123",
"DEMOPASS2026",
"Demo_Pass_2026",
"blue demo tractor sandwich",
"emily.carter-portal-2026",
]
No regex, no library: this version lists every rule a password misses:
from test_passwords import PASSWORDS
def check_password(pw):
missing = []
if len(pw) < 8:
missing.append("8+ chars")
if not any(c.islower() for c in pw):
missing.append("lowercase")
if not any(c.isupper() for c in pw):
missing.append("uppercase")
if not any(c.isdigit() for c in pw):
missing.append("digit")
if all(c.isalnum() for c in pw):
missing.append("symbol")
return missing
for pw in PASSWORDS:
missing = check_password(pw)
print(f"{pw:28} {'OK' if not missing else ', '.join(missing)}")
Output:
abc123 8+ chars, uppercase, symbol
DEMOPASS2026 lowercase, symbol
Demo_Pass_2026 OK
blue demo tractor sandwich uppercase, digit
emily.carter-portal-2026 uppercase

Only Demo_Pass_2026 passes. The 26-character passphrase fails for lack of an uppercase letter and a digit.
Each rule is one test over the characters, and Python any() function stops at the first match.
all(c.isalnum() ...) is true when there’s no symbol, so a space counts as one.
Wrap it in a function like this and you have a reusable password validator in Python.
Python Password Validation with a Regex
Same five passwords, now checked by one pattern built from lookaheads:
import re
from test_passwords import PASSWORDS
RULES = re.compile(r"""
(?=.*[a-z]) # lowercase
(?=.*[A-Z]) # uppercase
(?=.*\d) # digit
(?=.*[^A-Za-z0-9]) # symbol (space counts)
.{8,64} # 8 to 64 characters
""", re.VERBOSE)
for pw in PASSWORDS:
print(f"{pw:28} {bool(RULES.fullmatch(pw))}")
Output:
abc123 False
DEMOPASS2026 False
Demo_Pass_2026 True
blue demo tractor sandwich False
emily.carter-portal-2026 False

Same verdicts, but your users get no reasons.
Each (?=...) lookahead checks for one character type, .{8,64} sets the length, and fullmatch() anchors both ends.
You’ll find more on lookaheads in my regular expressions in Python tutorial.
Check Passwords the NIST Way: Length and a Blocklist
NIST SP 800-63B (Revision 4, final in July 2025) turned these rules around. A password used as the only factor needs at least 15 characters, or 8 when it’s part of multi-factor sign-in.
It also says to allow at least 64 characters, skip forced character mixes, reject common or breached passwords and drop scheduled resets.
Here’s that policy in Python as nist_check.py:
from test_passwords import PASSWORDS
COMMON = {"abc123", "password123", "qwerty123", "letmein123"}
def nist_check(pw, username, mfa=False):
min_len = 8 if mfa else 15
if pw.lower() in COMMON:
return "on the common-password list"
if len(pw) < min_len:
return f"too short (min {min_len})"
if len(pw) > 64:
return "too long (max 64)"
if username.lower() in pw.lower():
return "contains the username"
return "OK"
if __name__ == "__main__":
for pw in PASSWORDS:
print(f"{pw:28} {nist_check(pw, 'emily.carter')}")
Output:
abc123 on the common-password list
DEMOPASS2026 too short (min 15)
Demo_Pass_2026 too short (min 15)
blue demo tractor sandwich OK
emily.carter-portal-2026 contains the username

Now only the passphrase is accepted. Demo_Pass_2026 is too short at 14 characters (it would pass with MFA), and the last one contains the username.
Note: COMMON is a stand-in. A real Python app loads a breached-password list or queries Have I Been Pwned.
The same sign-up form needs an address check too, which I cover in validating email addresses in Python.
How Do You Make a Password Checker in Python?
A password checker in Python asks, checks and asks again. getpass() hides the typing, unlike input():
from getpass import getpass
from nist_check import nist_check
while True:
pw = getpass("New password: ")
result = nist_check(pw, "emily.carter")
if result == "OK":
break
print(f"Rejected: {result}. Try again.")
print("Password accepted.")
Output:
New password:
Rejected: too short (min 15). Try again.
New password:
Rejected: contains the username. Try again.
New password:
Password accepted.

I typed three passwords: two rejected with a reason, then the passphrase got through.
That shot is Command Prompt, since getpass needs a real console. For visible prompts, the input() function in Python works the same way.
Hash the Password Before You Store It
Never store the plain text. Store a slow, salted hash with Python’s built-in hashlib.scrypt():
import hashlib
import hmac
import secrets
def scrypt(pw, salt):
return hashlib.scrypt(pw.encode(), salt=salt, n=2**14, r=8, p=1)
salt = secrets.token_bytes(16)
stored = salt + scrypt("blue demo tractor sandwich", salt)
print("Stored bytes:", len(stored))
for guess in ["blue demo tractor sandwich", "blue demo tractor"]:
ok = hmac.compare_digest(scrypt(guess, stored[:16]), stored[16:])
print(f"{guess!r}: {ok}")
Output:
Stored bytes: 80
'blue demo tractor sandwich': True
'blue demo tractor': False
That’s 80 bytes: a 16-byte salt plus a 64-byte key. Only the right passphrase verifies.
hmac.compare_digest() compares in constant time. Plain SHA-256 from hash functions in Python is too fast for passwords; bcrypt and argon2-cffi also work.
Password Validation Problems That Lock Out Real Users
Most Python password bugs you’ll meet come from these habits:
- Stripping spaces or silently truncating. Passphrases need every character.
- Capping length at 16 or 20. Allow at least 64.
- Forcing resets on a timer. Change passwords after a breach instead.
- Checking only in the browser. Repeat it on the server (Flask, FastAPI, Django).
For a full sign-in flow with these checks, see this Django login system walkthrough.
Password validation in Python works best as length plus a blocklist, with clear reasons and a hash at the end.
Building the rest of that sign-up screen? Try these next:
- Generate a random string of a set length in Python
- Validate Tkinter entry fields
- Validate forms in Django
- Use Python’s all() function
Questions About Python Password Validation
How do I validate a password in Python without regex?
Use any() with isupper(), isdigit() and friends, collecting each failed rule.
What is a good regex for password validation in Python?
One lookahead per character type plus .{8,64}, with re.fullmatch().
How long should a password be?
NIST SP 800-63B asks for 15+ characters as the only factor, 8+ with MFA.
Should a password require special characters?
NIST says no. Length plus a blocklist stops more weak passwords.
Why does getpass show a warning in my IDE?
Some IDE consoles can’t hide input, so it warns and echoes. Use a real terminal.
How should I store passwords in Python?
Store a salted, slow hash, never the password. See hashlib on docs.python.org for scrypt().

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and