Form Validation
Let's see how to validate form data.
We'll cover the following...
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:
Press + to interact
<?phpif ($_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 ...
Access this course and 1400+ top-rated courses and projects.