Data Validation Techniques
1. Presence Check
- Ensures that required fields are not left empty.
- Commonly used in forms where specific fields must be filled out.
data = input("Enter your name: ")
if data.strip() == "":
print("Error: This field cannot be empty.")
else:
print("Valid input!")
2. Length Check
- Ensures that the input meets a specified length requirement (minimum or maximum).
data = input("Enter a password (min 8 characters): ")
if len(data) < 8:
print("Error: Password must be at least 8 characters long.")
else:
print("Valid password!")
3. Data Type Check
- Validates that the input matches the expected data type (e.g., integer, float, string).
data = input("Enter a number: ")
if data.isdigit():
print("Valid input!")
else:
print("Error: Input must be a number.")
4. Format Check
- Ensures that the input follows a specific format (e.g., email address, phone number).
data = input("Enter an email address: ")
symbol_count = 0
for char in data:
if char = '@':
symbol_count += 1
if count = 1:
print("Valid email!")
else:
print("Error: Invalid email format.")
print("Error: Invalid email format.")
5. Range Check
- Ensures that numerical input falls within a specified range.
data = int(input("Enter a number between 1 and 100: "))
if 1 <= data <= 100:
print("Valid input!")
else:
print("Error: Number out of range.")
6. Existence Check
- Verifies that the input exists in a predefined list or database.
valid_users = ["Alice", "Bob", "Charlie"]
data = input("Enter your username: ")
if data in valid_users:
print("Valid username!")
else:
print("Error: Username does not exist.")
7. Check Digit
- Validates numerical identifiers (e.g., ISBN, credit card numbers) using algorithms.
- The calculation of the check digit depends on the question.
- The given code is just an example, that you do not have to memorise.
# Example: Simple Mod-10 Check
data = "12345678"
check_digit = int(data[-1])
calculated_digit = sum(int(digit) for digit in data[:-1]) % 10
if check_digit == calculated_digit:
print("Valid check digit!")
else:
print("Error: Invalid check digit.")