2.8 Validation
2.8.1 Validation checks
Definition and Purpose of Validation
Definition: Validation is the process of checking that
input data is reasonable, sensible, and acceptable before processing.
Purpose: To prevent errors, incorrect processing, and potential security issues.
When used: Whenever user input or external data is entered.
Purpose: To prevent errors, incorrect processing, and potential security issues.
When used: Whenever user input or external data is entered.
Presence Check
Ensures that data has been entered.
Python example:
Python example:
name = input("Enter name: ")
if name == "":
print("Name is required")
Length Check
Ensures data is within an acceptable length.
Python example:
Python example:
password = input("Enter password: ")
if len(password) < 8:
print("Password too short")
Range Check
Ensures numeric data falls within a defined range.
Python example:
Python example:
age = int(input("Enter age: "))
if age < 0 or age > 120:
print("Age out of range")
Type Check
Ensures data is of the correct type.
Python example:
Python example:
value = input("Enter a number: ")
if not value.isdigit():
print("Not a valid number")
Format Check
Checks data follows a specific pattern.
Python example:
Python example:
email = input("Enter email: ")
if "@" not in email:
print("Invalid email format")
Check Digit
Uses a calculated digit to verify data accuracy.
Example use: Barcodes, ISBNs.
Simple Python concept example:
Example use: Barcodes, ISBNs.
Simple Python concept example:
number = "1234"
check_digit = int(number[-1])
if check_digit % 2 == 0:
print("Check digit valid")
2.8.2 Interpreting validation code
Interpreting Code Using Validation
Example:
mark = int(input("Enter mark: "))
if mark >= 0 and mark <= 100:
print("Valid mark")
This checks that the input is within an acceptable range.
2.8.3 Developing code using validation
Developing Validation Code
Python example:
username = input("Enter username: ")
if username != "" and len(username) >= 5:
print("Username accepted")
else:
print("Invalid username")
2.8.4 Debugging validation code
Debugging Validation Code
Incorrect code:
Corrected code:
age = input("Enter age: ")
if age > 18:
print("Adult")
Problem: Input is a string, not an integer.
Corrected code:
age = int(input("Enter age: "))
if age > 18:
print("Adult")