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.
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:
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 ...