Course contentsShow
← Security
Lesson 1155 of 3,05224. Application Security - Input ValidationFree lesson

Rejecting vs Sanitizing Invalid Input

Decide when to reject invalid input entirely versus attempting to sanitize or normalize problematic data.

Rejecting vs Sanitizing Invalid Input

What you'll learn: You'll learn when to outright reject invalid input versus when to attempt cleaning or transforming it for safe use.


When your application receives input that doesn't match expected validation rules, you face a critical decision: Should you reject it entirely and return an error, or should you attempt to sanitize (clean/normalize) it?

The Two Approaches

Rejecting means refusing to process invalid input at all. If a username field expects only alphanumeric characters and you receive admin<script>, you reject the entire request with an error message. The application never attempts to "fix" the input.

Sanitizing means attempting to transform invalid input into something acceptable. You might strip out <script> tags, encode special characters, or normalize Unicode—trying to extract valid data from potentially malicious input.

When to Reject

Reject invalid input when:

  • You control both sides: Internal APIs, admin panels, or systems where you control the client
  • The format is strict: Credit card numbers, dates, IDs—there's no ambiguity about what's valid
  • Security is paramount: Authentication tokens, file paths, SQL query components
  • The cost of mistakes is high: Financial transactions, access control decisions

Think of it like airport security: If your ID doesn't match requirements exactly, you don't get through. They don't try to "fix" your ID.

When to Sanitize

Consider sanitizing when:

  • User-generated content: Comments, forum posts, profile descriptions
  • You need flexibility: International names with special characters
  • Denial of service concerns: Rejecting too strictly might lock out legitimate users

However, always sanitize carefully based on the output context (HTML encoding, URL encoding, etc.), not by trying to remove "bad" characters.

Key Takeaway: Prefer rejecting invalid input in security-sensitive contexts; reserve sanitization for user-facing content where you can safely transform data for its specific output context—but never trust sanitization as your primary defense.