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:

<form method="post" action="this-page.php">
    <label>Name<input type="text" name="name"></label><br>
    <label>Email<input type="text" name="email"></label><br>
    <label>Extra Info<br><textarea name="extra_info"></textarea></label><br>
    <input type="submit" name="submit" value="Submit">
</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:

<?php
if(isset($_POST['submit'])){
    //Submit button has been pressed.
    echo 'Submit button pressed!';
}

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:

<?php
if(isset($_POST['submit'])){
    $name = isset($_POST['name']) ? $_POST['name'] : null;
    $email = isset($_POST['email']) ? $_POST['email'] : null;
    $extraInfo = isset($_POST['extra_info']) ? $_POST['extra_info'] : null;
}

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

$variableName = (TRUE OR FALSE CONDITION) ? (IF TRUE, DO THIS) : (IF FALSE, DO THIS)

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

<?php
if(isset($_POST['submit'])){
    $name = null;
    if(isset($_POST['name'])){
        $name = $_POST['name'];
    }
    $email = null;
    if(isset($_POST['email'])){
        $email = $_POST['email'];
    }
    $extraInfo = null;
    if(isset($_POST['extra_info'])){
        $extraInfo = $_POST['extra_info'];
    }
}

Note that I’m using isset because there is no guarantee that these form fields will exist! If you attempt to access a POST variable that does not exist, it will cause an undefined index warning.

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:

//Setup an empty array.
$errors = array(); 

//If our form has been submitted.
if(isset($_POST['submit'])){
    //Validate our fields and add errors to the $errors array.
}

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:

//Setup an empty array.
$errors = array(); 

//If our form has been submitted.
if(isset($_POST['submit'])){

    //Get the values of our form fields.
    $name = isset($_POST['name']) ? $_POST['name'] : null;
    $email = isset($_POST['email']) ? $_POST['email'] : null;
    $extraInfo = isset($_POST['extra_info']) ? $_POST['extra_info'] : null;

    //Check the name and make sure that it isn't a blank/empty string.
    if(strlen(trim($name)) === 0){
        //Blank string, add error to $errors array.
        $errors[] = "You must enter your name!";
    }
    //Make sure that the email address is valid.
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        //$email is not a valid email. Add error to $errors array.
        $errors[] = "That is not a valid email address!";
    }
}

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:

//Setup an empty array.
$errors = array(); 

//If our form has been submitted.
if(isset($_POST['submit'])){

    //Get the values of our form fields.
    $name = isset($_POST['name']) ? $_POST['name'] : null;
    $email = isset($_POST['email']) ? $_POST['email'] : null;
    $extraInfo = isset($_POST['extra_info']) ? $_POST['extra_info'] : null;

    //Check the name and make sure that it isn't a blank/empty string.
    if(strlen(trim($name)) === 0){
        //Blank string, add error to $errors array.
        $errors[] = "You must enter your name!";
    }
    //Make sure that the email address is valid.
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        //$email is not a valid email. Add error to $errors array.
        $errors[] = "That is not a valid email address!";
    }

    //If our $errors array is empty, we can assume that everything went fine.
    if(empty($errors)){
        //Send email or insert data into database.
    }
}

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?

<?php 
if(!empty($errors)){ 
    echo '<h1>Error(s)!</h1>';
    foreach($errors as $errorMessage){
        echo $errorMessage . '<br>';
    }
} 
?>

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