Wikis & learning

Return useful errors for form fields

A form handler needs to explain which fields need attention. Collect per-field errors before deciding whether to save the submission.

A form handler needs to explain which fields need attention. Collect per-field errors before deciding whether to save the submission.

Walkthrough

Start by checking the shape of each value. Then apply the rules for that field. An email validation checks the supplied address format; a separate verification step would be needed to establish ownership.

PHP example

<?php
$form = ['name' => '  Lee ', 'email' => 'not an address'];
$errors = [];
if (!is_string($form['name'] ?? null) || trim($form['name']) === '') {
    $errors['name'] = 'Enter a name';
}
if (!is_string($form['email'] ?? null) || !filter_var($form['email'], FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Enter an email address';
}
echo json_encode($errors);

Expected output

{"email":"Enter an email address"}

Change and check

Add a valid email and leave the name blank. Only the name should remain in the errors map. Then supply both values and check that the map is empty.