Master data validation techniques including presence, length, range, type, format, and check digit validation to ensure data integrity and prevent errors in your programs.
Ensures that required fields are not empty or missing
Prevent processing of incomplete data
Form fields, user registration, mandatory configuration settings
def validate_presence(value, field_name):
"""Check if required field has a value"""
if not value or value.strip() == "":
return False, f"{field_name} is required"
return True, "Valid"
# Example usage
username = input("Enter username: ")
is_valid, message = validate_presence(username, "Username")
if not is_valid:
print(f"Error: {message}")
else:
print("Username accepted")Checks that data meets minimum and maximum length requirements
Ensure data fits storage constraints and security requirements
Passwords, usernames, text fields, file names, database varchar limits
def validate_length(value, min_length=0, max_length=None, field_name="Field"):
"""Check if value meets length requirements"""
length = len(str(value))
if length < min_length:
return False, f"{field_name} must be at least {min_length} characters"
if max_length and length > max_length:
return False, f"{field_name} must be no more than {max_length} characters"
return True, "Valid"
# Example usage
password = input("Enter password: ")
is_valid, message = validate_length(password, 8, 16, "Password")
if not is_valid:
print(f"Error: {message}")Verifies numeric values fall within acceptable minimum and maximum bounds
Ensure numbers are realistic and within system limits
Ages, scores, quantities, measurements, financial amounts
def validate_range(value, min_val=None, max_val=None, field_name="Value"):
"""Check if numeric value is within acceptable range"""
try:
num_value = float(value)
except (ValueError, TypeError):
return False, f"{field_name} must be a number"
if min_val is not None and num_value < min_val:
return False, f"{field_name} must be at least {min_val}"
if max_val is not None and num_value > max_val:
return False, f"{field_name} must be no more than {max_val}"
return True, "Valid"
# Example usage
age = input("Enter age: ")
is_valid, message = validate_range(age, 0, 120, "Age")Ensures data matches the expected data type format
Prevent type errors and ensure data compatibility
Numeric inputs, boolean flags, date strings, file types
def validate_type(value, expected_type, field_name="Field"):
"""Check if value can be converted to expected type"""
try:
if expected_type == int:
int(value)
elif expected_type == float:
float(value)
elif expected_type == bool:
if str(value).lower() not in ['true', 'false', '1', '0']:
raise ValueError("Not a valid boolean")
return True, "Valid"
except (ValueError, TypeError):
type_name = expected_type.__name__
return False, f"{field_name} must be a valid {type_name}"
# Example usage
score = input("Enter test score: ")
is_valid, message = validate_type(score, float, "Test score")Checks data follows specific patterns or formats
Ensure structured data meets expected patterns
Email addresses, phone numbers, postcodes, credit card numbers, URLs
import re
def validate_email(email):
"""Check if email follows basic format pattern"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if re.match(pattern, email):
return True, "Valid email format"
return False, "Invalid email format"
def validate_uk_postcode(postcode):
"""Check UK postcode format"""
pattern = r'^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}$'
if re.match(pattern, postcode.upper()):
return True, "Valid UK postcode"
return False, "Invalid UK postcode format"
# Example usage
email = input("Enter email: ")
is_valid, message = validate_email(email)Uses mathematical algorithms to verify identifier authenticity
Detect errors in codes and prevent invalid identifiers
Credit cards, ISBN codes, barcodes, government ID numbers
def validate_luhn_checksum(card_number):
"""Validate credit card using Luhn algorithm"""
def luhn_checksum(card_num):
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_num)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = sum(odd_digits)
for d in even_digits:
checksum += sum(digits_of(d*2))
return checksum % 10
if luhn_checksum(card_number) == 0:
return True, "Valid card number"
return False, "Invalid card number"
def validate_isbn10(isbn):
"""Validate ISBN-10 check digit"""
if len(isbn) != 10:
return False, "ISBN must be 10 digits"
checksum = sum((i + 1) * int(digit) for i, digit in enumerate(isbn[:9]))
check_digit = (checksum % 11) % 11
if str(check_digit) == isbn[9] or (check_digit == 10 and isbn[9] == 'X'):
return True, "Valid ISBN-10"
return False, "Invalid ISBN-10"Validation performed in the user interface before submission
JavaScript form validation in web browsers
Validation performed on the server after data submission
Python validation functions processing form data
Combination of client-side and server-side validation
Real-time UI feedback plus secure server validation
Design comprehensive validation for a user registration form with all validation types
Implement user-friendly error messages and validation feedback systems
Create validation systems that prevent common security vulnerabilities