Skip to content

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.

Beginner 10 min read·Lesson 299 of 306 in Python Programming

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

Python
def parse_amount(text):
text = text.strip().replace(",", "")
try:
value = float(text)
except ValueError:
raise ValueError(f"not a number: {text!r}") from None
if value <= 0:
raise ValueError("amount must be positive")
return round(value, 2)
  • Normalise, convert, check.
  • Raise ValueError with a clear message.
  • Validate at the boundary.

Code examples

Validating amounts

Python
def parse_amount(text):
text = text.strip().replace(",", "")
try:
value = float(text)
except ValueError:
raise ValueError(f"not a number: {text!r}") from None
if value <= 0:
raise ValueError("amount must be positive")
if value > 1_000_000:
raise ValueError("amount looks too large")
return round(value, 2)
for raw in ["250", " 1,200.50 ", "abc", "-5", "5000000"]:
try:
print(raw.strip(), "->", parse_amount(raw))
except ValueError as e:
print(raw.strip(), "-> error:", e)
Output
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

Python
from datetime import datetime
CATEGORIES = {"food", "travel", "rent", "other"}
def parse_category(text):
category = text.strip().lower()
if category not in CATEGORIES:
raise ValueError(f"category must be one of {sorted(CATEGORIES)}")
return category
def parse_date(text):
return datetime.strptime(text.strip(), "%d/%m/%Y").date()
print(parse_category(" Food "), parse_date("27/11/2026"))
try:
parse_category("games")
except ValueError as e:
print(e)
Output
food 2026-11-27
category must be one of ['food', 'other', 'rent', 'travel']

More examples

Re-prompting and validating a whole form

Python
def ask(prompt, parser, answers):
while True:
raw = next(answers) # stands in for input(prompt)
try:
return parser(raw)
except ValueError as e:
print(f"{prompt} {raw!r} rejected: {e}")
def positive_float(text):
value = float(text)
if value <= 0:
raise ValueError("must be positive")
return value
def category(text):
if text not in {"food", "travel"}:
raise ValueError("unknown category")
return text
answers = iter(["abc", "250", "games", "food"])
amount = ask("amount", positive_float, answers)
cat = ask("category", category, answers)
print("saved:", amount, cat)
def validate_form(form):
errors = {}
if not form.get("name", "").strip():
errors["name"] = "required"
if "@" not in form.get("email", ""):
errors["email"] = "invalid email"
if not str(form.get("age", "")).isdigit():
errors["age"] = "must be a whole number"
return errors
print(validate_form({"name": " ", "email": "asha.example.com", "age": "2x"}))
print(validate_form({"name": "Asha", "email": "asha@example.com", "age": "30"}))
Output
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:

TextOutput
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'}
{}

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

def monthly_report(expenses):
for e in expenses:
if e.amount < 0: ... # checks scattered everywhere

Prefer

Validate when the expense is created, then trust it.

Scattered checks are easy to forget and duplicate effort.

Unhelpful messages

Avoid

raise ValueError("invalid input")

Prefer

raise ValueError("amount must be a positive number, e.g. 250 or 99.50")

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

  1. 1
    Write parse_phone that accepts Indian mobile numbers with optional +91 and spaces.
  2. 2
    Validate 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?
Practise this topic