Skip to main content

Input Validation Methods Quick Reference

Best Practices

  • Validate at every layer (client, server, database)
  • Whitelist over blacklist
  • Use prepared statements for all DB queries
  • Apply context-specific encoding on output
  • Fail securely — Reject invalid input
  • Log validation failures for security monitoring

Prevents

  • SQL Injection
  • XSS (Cross-Site Scripting)
  • Command Injection
  • Path Traversal
  • Buffer Overflow
  • DoS attacks

1. Client-Side Validation

(For better user experience, not actually secure)

  • HTML5: required, minlength, maxlength, pattern, type="email"
  • JavaScript validation before submission
  • Always validate server-side

2. Server-Side Validation

Purpose: Enforce security and data integrity

2.1 Whitelist

  • Define what IS allowed
  • More secure than blacklisting
  • Example: if role not in ['user', 'admin', 'moderator']

2.2 Blacklist

  • Define what is NOT allowed
  • Easy to bypass with variations
  • Example: Blocking <script> but not <ScRiPt>

2.3 Type Checking

  • Verify expected data types (int, string, bool)
  • Example: isinstance(age, int) or typeof age === 'number'

2.4 Length Checks

  • Prevent buffer overflows and DoS
  • Enforce min/max lengths
  • Example: if len(username) > 50: reject()

2.5 Format Validation

  • Regex for structured data (email, phone, URL)
  • Built-in validators when available
  • Example: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/

2.6 Sanitization

  • Context-specific encoding when outputting data:
    • HTML: HTML entity encoding (&lt;, &gt;)
    • SQL: Use prepared statements (parameterized queries)
    • JavaScript: Escape quotes and special chars
    • URL: URL encoding (%20)
  • Sanitization ≠ Validation (don't rely on it alone)

3. Database Layer

3.1 Prepared Statements (Critical)

  • Prevents SQL injection
  • Never concatenate user input into queries
  • cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
  • cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")

3.2 Database Constraints

  • NOT NULL — Require value
  • UNIQUE — Prevent duplicates (username, email)
  • CHECK — Custom validation (e.g., age >= 18)
  • FOREIGN KEY — Referential integrity
  • DEFAULT — Set default values