More data validation in PHP

This tutorial shows some more data validation methods following on from the form data validation tutorial. In this tutorial, you will be shown how to implement the following data validation methods:

  • Limit number of characters that can be entered in a text box
  • Ask the user to enter a password twice and check that both passwords are identical
  • Validate an email address
  • Check that all parts of a form are completed

Watch the video below and then scroll down to see the sample code.

Sample PHP code

There are two files being used in this example which will validate a username, email address and password. The files are form.php and action_handler.php.

The form.php code:

<html>
<head>
  <title>Form that validates data</title>
</head>
<body>
  <form action="action_handler.php" method="POST">
    <h3>Enter a username, email and password to sign up.</h3>
    <p>Username: <input type="text" name="username"></p>
    <p>Email address: <input type="text" name="email"></p>
    <p>Password: <input type="password" name="password"></p>
    <p>Password again: <input type="password" name="password2"></p>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>

The action_handler.php code:

<?php
  if(!empty($_POST['username'])){
    $username = $_POST['username'];
    if(strlen($username) > 30){
      $username = NULL; echo "Username cannot be longer than 30 characters.<br/>";
    }
  }
  else{
    $username = NULL; echo "You must enter a username.<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.<br/>";
    }
  }
  else{
    $email = NULL; echo "You must enter an email address.<br/>";
  }

  if(!empty($_POST['password']) || !empty($_POST['password2'])){
    $password = $_POST['password'];
    $password2 = $_POST['password2'];
    if($password != $password2){
      $password = NULL; $password2 = NULL; echo "Both passwords must be the same.<br/>";
    }

  }
  else{
    $password = NULL; $password2 = NULL; echo "You must enter your password twice.";
  }

  if(strlen($password) <10 && strlen($password2) <10){
    $password=NULL;$password2=NULL;echo "Password must be 10 characters or longer<br/>";
  }

  if(($username != NULL) && ($email != NULL) && ($password != NULL) && ($password2 != NULL)){
    $passwordLength = strlen($password);
    $hiddenPassword= "$password[0]"."$password[1]".str_repeat("*",($passwordLength-2));
    echo "<h3>Thank you for registering. Here are your details...</h3>";
    echo "Username: $username <br/>Email: $email<br/>Password: $hiddenPassword";
  }
?>