📖 Worked Example: Registration Form Validation
Follow along as we build robust input validation step by step!
Validation Type Reference
| Type | Purpose | Code Pattern | Example Use |
|---|---|---|---|
| Presence | Not empty | if x == "": |
Required fields |
| Range | Within limits | if x < min or x > max: |
Age 0-120, Score 0-100 |
| Length | Correct size | if len(x) < n: |
Password min 8 chars |
| Format | Matches pattern | if "@" not in x: |
Email contains @ |
| Type | Correct data type | if not x.isdigit(): |
Numbers only |
Input Sanitisation Techniques
sanitisation_examples.py
# Remove leading/trailing whitespace
name = input("Name: ").strip()
# Convert to lowercase for comparison
choice = input("Yes/No: ").lower()
# Remove dangerous characters (SQL injection prevention)
def sanitise_sql(text):
dangerous = ["'", '"', ";", "--"]
for char in dangerous:
text = text.replace(char, "")
return text
# Keep only alphanumeric characters
def clean_username(text):
result = ""
for char in text:
if char.isalnum():
result = result + char
return result