Why is input validation important?

SecurityJavaScript

What is Input Validation?

Input validation is the process of ensuring that data entered by a user (or received by an application) meets specific criteria before it is processed. This includes checking for correct data types, formats, lengths, and ranges.

Importance in Security

Input validation is a primary line of defense against many security vulnerabilities. Trusting user input blindly is one of the most common causes of security breaches.

1. Preventing Injection Attacks

Without validation, malicious scripts can be injected into the application.

  • XSS (Cross-Site Scripting): If an application allows users to input HTML or JavaScript and displays it without validation or escaping, attackers can execute malicious scripts in other users' browsers.
  • SQL Injection: (Backend context) If input isn't validated or sanitized before being used in database queries, attackers can manipulate the database.

2. Data Integrity

Ensures that the data stored is clean and usable. For example, ensuring an age field only contains numbers prevents errors when creating charts or calculations later.

3. Availability (DoS)

Maliciously crafted excessively long inputs could cause an application to crash or consume excessive resources, leading to a Denial of Service.

Client-side vs. Server-side Validation

It is crucial to understand the distinction between the two:

  • Client-side Validation (UX): Happens in the browser (Javascript/HTML). It provides immediate feedback to the user (e.g., "Email is required"). It is not a security measure because it can be easily bypassed by disabling JavaScript or using tools like Postman.
  • Server-side Validation (Security): Happens on the server. This is the actual security layer. The server must never trust the client and must validate all incoming data, regardless of what checks were done on the frontend.

Sanitization over Manual Validation

While validation checks if the input is correct (e.g., "is this an email?"), sanitization cleans the input to remove unsafe characters.

Attempting to "sanitize" input manually (e.g., writing your own regex to replace < and >) is dangerous and error-prone. Hackers often find ways around custom filters.

Recommended Approach: DOMPurify

Instead of writing your own sanitization logic, use battle-tested libraries like DOMPurify. It strips out dangerous HTML and scripts while keeping safe HTML intact.

import DOMPurify from 'dompurify';

const userComment = '<img src=x onerror=alert("Hacked!")>';

// ❌ Dangerous: This executes the alert
document.getElementById('comment').innerHTML = userComment;

// ✅ Safe: DOMPurify removes the onerror event
const cleanComment = DOMPurify.sanitize(userComment);
// Result: <img src="x">
document.getElementById('comment').innerHTML = cleanComment;

This ensures that even if a malicious script slips through validation, it is rendered harmless before being displayed to other users.

00:00