Documentation · Chapter 08

Validate on input,
escape on output.

These operations answer two different questions: is the value acceptable, then can it be displayed without becoming HTML code?

We secure reading-list in layers without pretending one option is enough.

Validation protects rules

phpaml — zsh
$validator = new Validator();

$valid = $validator->validate($request->input(), [
    'title' => ['required', 'string', 'min:2', 'max:180'],
    'author' => ['required', 'string', 'min:2', 'max:120'],
]);

if (!$valid) {
    return $this->view('books/create.php', [
        'errors' => $validator->errors(),
        'old' => $request->input(),
    ], 422);
}

required checks presence, string checks type, and min/max check length. PHPAML also provides email, url, uuid, integer, numeric, boolean, date, in, same, confirmed, regex, unique, and exists.

Escaping protects the document

phpaml — zsh
<!-- Mauvais : le contenu peut devenir du HTML -->
<h1><?= $book->title ?></h1>

<!-- Bon : le contenu reste du texte -->
<h1><?= $view->escape($book->title) ?></h1>

A title such as <script>…</script> must be displayed literally, never executed. Escape when producing HTML output because the correct encoding depends on output context.

Do not silently repair invalid input

trim() may remove accidental whitespace, but silently transforming an invalid value can change user intent. Preserve safe old values, show errors near fields, and return 422.

Check your understanding: Does validation replace escape()?

No. A title containing some HTML characters may be valid data, but must still be escaped when displayed.