Validation Patterns
beginner10 min readLesson 15 of 169
Decisions with a job: checking inputs before trusting them.
Real programs check inputs before trusting them. Validation is just decisions with a job:
hour = 25 # from user input somewhere
if not 0 <= hour <= 23:
print("invalid hour")
The validation pattern
- Check the shape of the data (is it present? the right type?).
- Check the range/domain (is it sensible?).
- Fail early with a clear message; otherwise proceed.
username = "ab"
if len(username) < 3:
print("too short: need at least 3 characters")
elif " " in username:
print("no spaces allowed")
else:
print("welcome,", username)
A validator is the perfect mini project: pure decisions, immediate feedback, and it is exactly what every real backend does before touching a database.