Area 2.8

Validation

Master data validation techniques including presence, length, range, type, format, and check digit validation to ensure data integrity and prevent errors in your programs.

6
Validation Types
3
Strategies
~2hrs
Study Time

Learning Objectives

  • Implement presence validation to ensure required data is provided
  • Apply length validation for appropriate data size limits
  • Use range validation to check numeric values are within acceptable bounds
  • Perform type validation to ensure correct data formats
  • Implement format validation for structured data like emails and phone numbers
  • Apply check digit validation for verification codes and identifiers

Validation Techniques

Presence Validation

Ensures that required fields are not empty or missing

Purpose:

Prevent processing of incomplete data

Examples:

  • Username must be provided
  • Email address required
  • Password cannot be blank

Common Uses:

Form fields, user registration, mandatory configuration settings

Python Implementation:

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")

Length Validation

Checks that data meets minimum and maximum length requirements

Purpose:

Ensure data fits storage constraints and security requirements

Examples:

  • Password 8-16 characters
  • Phone number exactly 11 digits
  • Username 3-20 characters

Common Uses:

Passwords, usernames, text fields, file names, database varchar limits

Python Implementation:

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}")

Range Validation

Verifies numeric values fall within acceptable minimum and maximum bounds

Purpose:

Ensure numbers are realistic and within system limits

Examples:

  • Age 0-120 years
  • Test score 0-100%
  • Temperature -50 to +50°C

Common Uses:

Ages, scores, quantities, measurements, financial amounts

Python Implementation:

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")

Type Validation

Ensures data matches the expected data type format

Purpose:

Prevent type errors and ensure data compatibility

Examples:

  • Integer for age
  • Float for price
  • Boolean for yes/no
  • Date for birth date

Common Uses:

Numeric inputs, boolean flags, date strings, file types

Python Implementation:

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")

Format Validation

Checks data follows specific patterns or formats

Purpose:

Ensure structured data meets expected patterns

Examples:

  • Email format: user@domain.com
  • Phone: +44 7123 456789
  • UK postcode: SW1A 1AA

Common Uses:

Email addresses, phone numbers, postcodes, credit card numbers, URLs

Python Implementation:

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)

Check Digit Validation

Uses mathematical algorithms to verify identifier authenticity

Purpose:

Detect errors in codes and prevent invalid identifiers

Examples:

  • ISBN book codes
  • Credit card numbers (Luhn algorithm)
  • UK National Insurance numbers

Common Uses:

Credit cards, ISBN codes, barcodes, government ID numbers

Python Implementation:

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 Strategies

Client-Side Validation

Validation performed in the user interface before submission

Advantages:

  • Immediate feedback
  • Better user experience
  • Reduces server load

Disadvantages:

  • Can be bypassed
  • Not secure
  • Limited validation capability

Example:

JavaScript form validation in web browsers

Server-Side Validation

Validation performed on the server after data submission

Advantages:

  • Cannot be bypassed
  • Secure and reliable
  • Full validation capability

Disadvantages:

  • Slower feedback
  • Requires server round-trip
  • More server resources

Example:

Python validation functions processing form data

Hybrid Validation

Combination of client-side and server-side validation

Advantages:

  • Best user experience
  • Secure and reliable
  • Optimized performance

Disadvantages:

  • More complex to implement
  • Duplicate validation logic
  • Higher development time

Example:

Real-time UI feedback plus secure server validation

Learning Activities

Input Validation System Design

Design
50 minutes

Design comprehensive validation for a user registration form with all validation types

Validation Error Handling Workshop

Implementation
45 minutes

Implement user-friendly error messages and validation feedback systems

Security Validation Challenge

Security
40 minutes

Create validation systems that prevent common security vulnerabilities