Search⌘ K

Form Validation

Explore how to validate form input effectively in PHP by normalizing data, displaying precise error messages next to form fields, and saving only valid data to JSON storage. This lesson helps you build a robust form validation process essential for reliable CRUD applications.

Stopping execution of the wrong data

Instead of saving an empty destination, we would want to say to the user: “Please fill in a destination”. Preferably, we would show this message next to the form field that it applies to. We can do this by taking a closer look at the submitted data and by stopping the execution if there’s something wrong:

PHP
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['destination']) || $_POST['destination'] === '') {
// Empty destination, don't save the data!
} else {
$toursData[] = [
'destination' =>
isset($_POST['destination'])
? (string)$_POST['destination']
: '',
'number_of_tickets_available' =>
isset($_POST['number_of_tickets_available'])
? (int)$_POST['number_of_tickets_available']
: 0,
'is_accessible' =>
isset($_POST['is_accessible'])
? true
: false
];
}
}

You can test this by submitting an empty form once more. You shouldn’t see another empty tour being added to tours.json.

Showing validation errors

However, the user doesn’t have any clue about what they did wrong. We should show a clear form error instead. Let’s define an array called $formErrors for this. Its keys will be form field names and its values the validation errors. As soon as we find ...