LOGBOOK

HELP

Quiz Entry - updated: 2026.07.31

Where should input validation, sanitization, and output encoding occur in MVC architecture?

Validate input in the Controller (entry), use prepared statements in the Model (DB), and encode output in the View (render). "Validate early, encode late."

Request flows User → Controller (validate + sanitize) → Model (prepared statements) → DB; response → View (output encoding) → User.

* MVC control placement — validate early in the Controller, parameterize in the Model, encode late in the View. *

Follow one request through the three layers and the placement stops being arbitrary:

Controller (input layer) — the first code that touches the request, so it is the cheapest place to throw bad data away:

  • Input validation — verify format, type and length, and reject what fails
  • Sanitization — clean or normalise what you keep

Validation and sanitization are not synonyms: validation is a yes/no verdict that rejects the whole input; sanitization modifies it (strips tags, trims, canonicalises) and lets it through. Prefer validation — sanitization is guesswork about what the user "meant", and a stripped payload can reassemble itself (<scr<script>ipt> survives a single removal pass).

Model (database layer) — where data meets the SQL interpreter:

  • Use prepared statements for all queries
  • Encoding/escaping for data going into the database

View (output layer) — where data meets the browser's parsers:

  • Output encoding/escaping immediately before rendering
  • Context-appropriate encoding (HTML, JS, URL, CSS)

Why encode late rather than on the way in? The correct escaping depends on the destination, and the same stored value may be rendered into an HTML body on one page, a JavaScript block on another and a URL on a third. Encode at input and you have committed to one destination, corrupted the stored data, and still got it wrong for the other two. Validate as early as you can; encode as late as you can — at the moment the output context is finally known.

Key principle: validate input early, encode output late, use prepared statements always.

From Quiz: SPRG / Input Validation & Output Encoding | Updated: Jul 31, 2026