Form data validation with PHP

This tutorial explains how to validate data that has been submitted by a user in a form. We will look at the following types of data validation:

  • Check that a text field has not been left empty
  • Check only numbers have been entered
  • Check that an email address is in the correct format

We will use the empty, is_numeric, and filter_var functions for data validation in this example. Watch the video below and then scroll down to see the sample code.

Sample PHP code

Step 1: Create a PHP file (eg. form.php) and copy the following code into that file. This file will contain the form.

  <title>Form that validates data</title>
  <form action="action_handler.php" method="POST">
    <h3>Enter a postcode and email address.</h3>
    <p>Post code: <input type="text" name="postcode"></p>
    <p>Email address: <input type="text" name="email"></p>
    <p><input type="submit" value="Submit"></p>

Step 2: Create a PHP file called action_handler.php and copy the following code into it. This file will handle the submitted form data.

    $postcode = $_POST['postcode'];
      $postcode = NULL; echo "Postcode must be numeric.<br/>";
    $postcode = NULL; echo "You must enter a postcode.<br/>";

    $email = $_POST['email'];
      $email = NULL; echo "Email address is not in the correct format.";
    $email = NULL; echo "You must enter an email address.<br/>";

  if(($postcode != NULL) && ($email != NULL)){
    echo "Email: $email<br/>Postcode: $postcode";