Simple form validation with PHP

Whether you like it or not, forms are a major apart of every web developer’s life. If you think about it, most of what we do is based on receiving and validating data that has been sent to us by the client. To sum it up, we receive data, we validate it and then we tell our application how to react.

Our form

I’m going to try and keep this simple, lest we muddy the waters with other topics that are better suited for individual posts. Here is an example of an extremely simple HTML form:

Note that we’ve got three fields:

  • A mandatory name field.
  • A mandatory email field.
  • An optional “Extra Info” field.

Validating with PHP

With this form, we’ve got four form fields that we need to pay attention to. Their names are “name”, “email”, “extra_info” and “submit.” That means that we will be dealing with four POST variables called “name”“email”“extra_info” and “submit.”

To figure out whether the form has been submitted or not, we can use the following piece of code:

In the above example, the isset function checks to see if a POST variable called “submit” exists. If it does, we make the assumption that the form has been submitted.

To get the values of our text fields, we can use the following piece of code:

In the above snippet, I am using the ternary operator, which basically equates to:

Without using ternary operators, my code would look something like this:

Note that I’m using isset because there is no guarantee that these form fields will exist!

When doing basic form validation with PHP, it can be useful to set up an errors array that will hold any UI errors that you want to display to the end user. Example:

As you can see, $errors is an empty array that will only be filled if the user has made a mistake. If the form fields are filled out correctly, our $errors array should be empty. If the array is not empty, we can assume that our user has messed up:

In the above example, you can see that UI errors are added to the $errors array if the user enters a blank/empty name or an invalid email address. We can use this array to our advantage:

Looking at the code above, you can see that the form is only processed IF the $errors array is empty. Otherwise, the form is ignored / discarded!

Finally: How do we display form errors to the user?

Basically, if the $errors array isn’t empty, we can assume that our form didn’t validate properly.