Learning objectives:
- Define validation and know when each check is used (2.8.1)
- Interpret, develop and debug code using validation (2.8.2–2.8.4)
What validation is
Validation is an automatic check that input data is sensible and reasonable before it is accepted. It cannot prove the data is correct: a valid date of birth can still be the wrong one.
The six validation checks
| Check | What it ensures | Example |
|---|---|---|
| Presence | A value has been entered, not left blank | Email cannot be empty |
| Length | The data has the right number of characters | Password at least 8 characters |
| Range | A number is between a minimum and maximum | Age 16 to 19 |
| Type | The data is the right type | Quantity must be a whole number |
| Format | The data follows a pattern | A postcode or an email address |
| Check digit | A code is valid, using an extra digit calculated from the others | Account numbers, barcodes |
You do not need to know a particular check digit algorithm, only what it is for.
Validation in Python
name = input("Name: ")
if name == "": # presence
print("Please enter your name.")
password = input("Password: ")
if len(password) < 8: # length
print("Password must be at least 8 characters.")
age_text = input("Age: ")
if not age_text.isdigit(): # type
print("Age must be a whole number.")
elif not 16 <= int(age_text) <= 19: # range
print("Age must be between 16 and 19.")
code = input("Class code (e.g. AB123): ")
if not (len(code) == 5 and code[:2].isalpha() and code[2:].isdigit()): # format
print("Use two letters then three numbers.")
Combine checks where needed, and repeat the question with a while loop until the data is valid.
Common validation bugs
- Range written as
age > 16 and age < 19, which wrongly rejects 16 and 19. - Converting with
int()before the type check, which crashes on text. orused whereandis needed, so every value passes.