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.

<html>
<head>
  <title>Form that validates data</title>
</head>
<body>
  <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>
  </form>
</body>

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.

<?php
  if(!empty($_POST['postcode'])){
    $postcode = $_POST['postcode'];
    if(!is_numeric($postcode)){
      $postcode = NULL; echo "Postcode must be numeric.<br/>";
    }
  }
  else{
    $postcode = NULL; echo "You must enter a postcode.<br/>";
  }

  if(!empty($_POST['email'])){
    $email = $_POST['email'];
    if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
      $email = NULL; echo "Email address is not in the correct format.";
    }
  }
  else{
    $email = NULL; echo "You must enter an email address.<br/>";
  }

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