Module 20 · Building Real Python Applications — topic 6 of 13
Input validation
Never trusting input: validating type, range, format and allowed values, normalising text, parsing dates, re-prompting until input is valid, collecting all errors in a form, and validating at the boundary of the application.
Learning objectives
- Validate numbers, choices and dates
- Re-prompt until input is valid
- Report all errors in a form at once
Definition
Input validation checks that data entering an application — from users, files or networks — is of the right type, within allowed ranges and in the expected format, before the application uses it.
Introduction
Users type 'abc' for an amount, '-5' for a price and ' Food ' for a category. Validation turns these into clear messages instead of crashes or bad data.
Why it matters
Invalid data that gets in spreads everywhere — wrong totals, corrupt files. Validating once, at the boundary, protects the rest of the program.
Detailed explanation
Validate at the boundary: where input enters (command line, form, file, API). Inside the program, code can then trust its data.
Check type (can it be converted to a number?), range (positive, not absurdly large), format (a date like DD/MM/YYYY) and allowed values (a known category).
Normalise before checking: strip spaces, lower-case categories, remove thousands separators.
Convert and validate in one parsing function that either returns a clean value or raises ValueError with a helpful message.
For interactive input, loop until a valid value is entered, showing what was wrong each time.
For forms, validate every field and report all errors together rather than one at a time.
Error messages should say what is expected ('category must be one of food, rent, travel'), not just 'invalid'.
Validation is not a security sanitiser: when data goes into SQL, HTML or shell commands, also use parameterised queries and escaping.
Syntax
- Normalise, convert, check.
- Raise ValueError with a clear message.
- Validate at the boundary.
Code examples
Validating amounts
250 -> 250.0 1,200.50 -> 1200.5 abc -> error: not a number: 'abc' -5 -> error: amount must be positive 5000000 -> error: amount looks too large
Choices and dates
food 2026-11-27 category must be one of ['food', 'other', 'rent', 'travel']
More examples
Re-prompting and validating a whole form
amount 'abc' rejected: could not convert string to float: 'abc'
category 'games' rejected: unknown category
saved: 250.0 food
{'name': 'required', 'email': 'invalid email', 'age': 'must be a whole number'}
{}Step-by-step explanation
- ask keeps calling the parser until it succeeds, showing each rejection.
- The parsers are reusable for files and command-line arguments too.
- validate_form checks every field and returns all problems, so a user can fix everything in one go.
Expected output
Running “Re-prompting and validating a whole form” prints exactly:
Practical applications
- Sign-up forms highlighting every invalid field.
- Import tools rejecting rows with bad amounts.
Best practices
- Validate at the boundary.
- Normalise before checking.
- Give specific, actionable messages.
Common mistakes
Validating deep inside the program
Avoid
Prefer
Scattered checks are easy to forget and duplicate effort.
Unhelpful messages
Avoid
Prefer
Users need to know what to type instead.
Important notes
- Libraries such as pydantic validate structured data declaratively using type hints.
Key takeaways
- Check type, range, format and allowed values.
- Re-prompt interactively; report all form errors at once.
- Validate once at the boundary.
Try it yourself
- 1Write parse_phone that accepts Indian mobile numbers with optional +91 and spaces.
- 2Validate a whole expense form (amount, category, date) and return all errors.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhere should input validation ideally happen?
- AdvancedWhat is printed?