Input Validation
Learn to check user input before using it - essential for robust, secure programs!
What you'll learn:
- Why validation is essential for good programs
- Five types of validation: Presence, Range, Length, Format, Type
- How to implement each validation check
- Input sanitisation and SQL injection prevention
Why Validate Input?
Never trust user input! Users might enter:
Accidental Mistakes
Typos, wrong format, empty fields
Unexpected Values
Negative ages, future dates, nonsense text
Malicious Input
SQL injection, code injection attacks
Solution: Validate!
Check ALL input before using it
The Five Types of Validation
Presence Check
What: Check that something was entered (not empty)
When: Required fields like name, email, password
name = input("Enter name: ")
if name == "":
print("Name is required!")
else:
print(f"Hello, {name}")
# Or more simply:
if not name:
print("Name is required!")
Range Check
What: Check a number is within acceptable limits
When: Ages, scores, quantities, percentages
age = int(input("Enter age: "))
if age < 0 or age > 120:
print("Age must be 0-120")
else:
print("Age accepted")
# Check score is 0-100
if 0 <= score <= 100:
print("Valid score")
Length Check
What: Check string has correct number of characters
When: Passwords, postcodes, phone numbers
password = input("Enter password: ")
if len(password) < 8:
print("Password must be at least 8 characters")
# Check postcode is 6-8 characters
if len(postcode) < 6 or len(postcode) > 8:
print("Invalid postcode length")
Format Check
What: Check data matches expected pattern
When: Email addresses, dates, phone numbers
email = input("Enter email: ")
# Simple email check
if "@" not in email:
print("Invalid email - must contain @")
# Check date format DD/MM/YYYY
date = input("Enter date (DD/MM/YYYY): ")
if len(date) != 10 or date[2] != "/" or date[5] != "/":
print("Invalid date format")
Type Check
What: Check data is the correct type (number, text, etc.)
When: Any numeric input from users
user_input = input("Enter a number: ")
# Check if it's a valid integer
if user_input.isdigit():
number = int(user_input)
print(f"You entered: {number}")
else:
print("That's not a valid number!")
# Using try/except (handles negatives too)
try:
number = int(user_input)
except ValueError:
print("Invalid number!")
Input Sanitisation & SQL Injection
What is SQL Injection?
SQL injection is a security attack where malicious code is inserted into input fields to manipulate database queries. It's one of the most common and dangerous web vulnerabilities!
Example Attack:
# DANGEROUS - Never do this!
username = input("Username: ")
query = "SELECT * FROM users WHERE name = '" + username + "'"
# If user enters: ' OR '1'='1
# Query becomes:
# SELECT * FROM users WHERE name = '' OR '1'='1'
# This returns ALL users - security breach!
How to Prevent SQL Injection
1. Parameterised Queries (Best!)
Use placeholders instead of string concatenation.
# SAFE - Use parameterised queries
cursor.execute(
"SELECT * FROM users WHERE name = ?",
(username,)
)
# The database treats input as data, not code
2. Input Sanitisation
Remove or escape dangerous characters.
# Remove dangerous characters
def sanitise(text):
dangerous = ["'", '"', ";", "--", "/*"]
for char in dangerous:
text = text.replace(char, "")
return text
clean_input = sanitise(user_input)
3. Whitelist Validation
Only allow expected characters.
# Only allow letters and numbers
def is_safe(text):
return text.isalnum()
if is_safe(username):
# Process the input
else:
print("Invalid characters!")
Complete Validation Loop
Keep asking until valid input is received:
# Keep asking until we get valid input
while True:
age_input = input("Enter your age (0-120): ")
# Type check - is it a number?
if not age_input.isdigit():
print("Please enter a number!")
continue
age = int(age_input)
# Range check - is it reasonable?
if age < 0 or age > 120:
print("Age must be between 0 and 120!")
continue
# Valid! Exit the loop
break
print(f"Your age is {age}")
Learning Path
Follow these activities in order.
1. Predict: Validation Results
Predict which inputs will pass validation checks.
2. Study: Worked Example
See how to implement validation step by step.
3. Investigate: Trace Validation
Track how validation checks process different inputs.
4. Modify: Arrange the Code
Put code blocks in order to create validation.
5. Test: Knowledge Quiz
Check your understanding of input validation.
Key Vocabulary
validation
Checking that input meets specific requirements before using it.
presence check
Verifying that a field is not empty.
range check
Verifying a number falls within acceptable limits.
length check
Verifying a string has the correct number of characters.
format check
Verifying data matches an expected pattern (e.g., email format).
type check
Verifying data is the correct type (number, text, etc.).
sanitisation
Cleaning input by removing or escaping dangerous characters.
SQL injection
A security attack using malicious input to manipulate database queries.
Quick Reference
# PRESENCE CHECK - not empty
if name == "":
print("Field required")
# RANGE CHECK - within limits
if age < 0 or age > 120:
print("Out of range")
# LENGTH CHECK - correct length
if len(password) < 8:
print("Too short")
# FORMAT CHECK - matches pattern
if "@" not in email:
print("Invalid email")
# TYPE CHECK - correct data type
if not user_input.isdigit():
print("Not a number")
# SANITISATION - remove dangerous chars
clean = text.replace("'", "").replace(";", "")