How to Handle Form Validation using PHP

How to Handle Form Validation using PHP

In this article, I will cover how to validate text fields, passwords, emails and URLs using PHP.

Despite providing detailed instructions for your users in your forms, most of them submit incorrect data. To prevent this, you can validate the user's input to ensure they provide the right information.

You can use front-end features such as the required attribute or input types to validate data. However, this is not recommended because the user can manipulate the website's source code on their browser and send invalid data.

In this article, you will learn how to validate user input and display the relevant error messages.

Prerequisites

  • HTML and CSS

  • PHP

  • XAMPP installed or your preferred Apache environment

You can find the source code for this tutorial here.

Creating the form

  1. Create a directory in the htdocs called form-validation

  2. Inside the form-validation directory, create a file called index.php

  3. Create a form with the following input types:

    • text,

    • email,

    • URL,

    • password,

💡
Add a name attribute to every input.

This is my version of the form. I am using Bootstrap for styling:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Validation</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>

<body>
    <section class="p-5">
        <h1 class="text-center">Sign Up</h1>
        <p class="text-center fst-italic">Please enter all the fields</p>
        <form action="" method="post" class="w-25 mx-auto">
            <div class="mb-3">
                <label for="name" class="form-label">Name</label>
                <input type="text" class="form-control" id="name" name="name">
            </div>
            <div class="mb-3">
                <label for="email" class="form-label">Email address</label>
                <input type="email" class="form-control" id="email" name="email">
            </div>
            <div class="mb-3">
                <label for="portfolio" class="form-label">Portfolio Link</label>
                <input type="url" class="form-control" id="portfolio" name="portfolio">
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input type="password" class="form-control" id="password" name="password">
            </div>

            <input type="submit" value="Sign Up" class="btn btn-outline-primary">
        </form>
    </section>


    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
</body>

</html>

This is how the form will look:

How to Validate for Empty Inputs in PHP

If the user has submitted an empty input, you should display an error message.

At the beginning of your index.php, create a PHP function that:

  1. takes an array of inputs

  2. checks for an empty field

  3. returns true or false

<?php
function checkForEmpty($inputFields)
{
    foreach ($inputFields as $inputField) {
        if (empty($inputField)) {
            return true;
        }
    }
    return false;
}
?>

Use the function to check if your inputs are empty after they are submitted.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $url = filter_input(INPUT_POST, 'portfolio', FILTER_SANITIZE_URL);
    $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_SPECIAL_CHARS);
    if (checkForEmpty([$name, $email, $url, $password])) {
        echo "Please fill all the fields";
    }
}
?>

Test if the code is working by submitting empty fields. The output will be:

The function executes successfully.

However, the error message is misplaced. I will cover how to display the error messages later in this blog.

How to Validate Text in PHP

In this section, you will learn how to use regular expressions to check for alphabetic characters and spaces.

Create a function that:

  1. takes a string as a parameter

  2. check if the string matches the regular expression

  3. return true or false

<?php
function checkForInvalidText($string)
{
    if (!preg_match("/^[a-zA-z]*$/", $string)) {
        return true;
    }
    return false;
}
?>

Use the function to check if the name is valid.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);

    // check if the user entered a valid name
    if (checkForInvalidText($name)) {
        echo "Please enter only characters and spaces";
    }
}
?>

The output will be:

How to Validate Email in PHP

In this section, you will use PHP's built-in function to validate the user's email.

Create a function that:

  1. takes an email as a parameter

  2. checks if the email is valid

  3. returns true or false

<?php
function checkForInvalidEmail($str)
{
    if (!filter_var($str, FILTER_VALIDATE_EMAIL)) {
        return true;
    }
    return false;
}
?>

Use the function to validate the user's email

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);

    // check if the email is valid
    if (checkForInvalidEmail($email)) {
        echo "Please enter a valid email";
    }
}
?>

The output will be:

How to Validate URL in PHP

Similarly, URL validation uses PHP's built-in functions.

Create a function that:

  1. takes a URL as a parameter

  2. validates the URL

  3. returns true or false

<?php
function checkForInvalidURL($str)
{
    if (!filter_var($str, FILTER_VALIDATE_URL)) {
        return true;
    }
    return false;
}
?>

Use the function to validate the user's URL

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $url = filter_input(INPUT_POST, 'portfolio', FILTER_SANITIZE_URL);

    // check if the URL is valid
    if (checkForInvalidEmail($url)) {
        echo "Please enter a valid URL";
    }
}
?>

This will be the output once you enter an invalid URL:

How to Validate Passwords in PHP

You will validate the password by matching the user's input with a regular expression. The user's input should have:

  • a lowercase letter

  • an uppercase letter

  • a number

  • special characters

Create a function that checks if a string matches the regular expression.

<?php
function checkForInvalidPassword($password){
    $regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$";
    if (!preg_match($regex, $password)) {
        return true;
    }
    return false;
}
?>

Use the function to check if the password is valid.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_SPECIAL_CHARS);

    // check if the password is valid
    if (checkForInvalidPassword($password)) {
        echo "Please enter a strong password";
    }
}
?>

Once you enter a password that does not meet the requirements, your output should be:

How to Display Error Messages

You will be displaying error messages after the respective input field and utilizing session variables to store them.

  1. Modifying the HTML code to add a tag to store the error messages

     <form action="" method="post" class="w-25 mx-auto" style="min-width: 300px;">
          <div class="mb-3">
             <label for="name" class="form-label">Name</label>
             <input type="text" class="form-control" id="name" name="name">
             <div class="invalid-feedback"></div>
          </div>
          <div class="mb-3">
             <label for="email" class="form-label">Email address</label>
             <input type="email" class="form-control" id="email" name="email">
             <div class="invalid-feedback"></div>
          </div>
          <div class="mb-3">
             <label for="portfolio" class="form-label">Portfolio Link</label>
             <input type="text" class="form-control" id="portfolio" name="portfolio">
             <div class="invalid-feedback"></div>
          </div>
          <div class="mb-3">
              <label for="password" class="form-label">Password</label>
              <input type="password" class="form-control" id="password" name="password">
              <div class="invalid-feedback"></div>
              <div class="form-text">
                 Your password should have:
                 <ul>
                   <li>at least one lowercase letter</li>
                   <li>at least one uppercase letter</li>
                   <li>at least one number</li>
                   <li>at least one special character</li>
                </ul>
            </div>
         </div>
    
        <input type="submit" value="Sign Up" class="btn btn-outline-primary">
     </form>
    
  2. Modifying the validation code

    You will make a few adjustments to your form validation code to ensure that every input has an error message. You will need to validate the fields individually to get the relevant error.

     <?php
     // checking if individual inputs are empty
     function checkForEmpty($inputField)
     {
       if (empty($inputField)) {
            return true;
       }
       return false;
     }
    
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
         $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
         $url = filter_input(INPUT_POST, 'portfolio', FILTER_SANITIZE_URL);
         $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_SPECIAL_CHARS);
    
          // validating the name
         if (checkForEmpty($name)) {
             $nameError = "Please enter your name";
         }elseif(checkForInvalidText($name)){
             $nameError = "Please only use characters and spaces. No special characters";
         }
         // validating the email
         if (checkForEmpty($email)) {
             $emailError = "Please enter your email";
         }elseif(checkForInvalidEmail($email)){
             $emailError = "Please enter a valid email address";
         }
    
         //validating the URL
         if (checkForEmpty($url)) {
             $urlError = "Please enter your portfolio link";
         }elseif(checkForInvalidURL($url)){
             $urlError = "Please enter a valid URL";
         }
    
         // validating the password
         if (checkForEmpty($password)) {
             $passwordError = "Please enter your password";
         }elseif(checkForInvalidPassword($password)){
             $passwordError = "Please use a strong password";
         }
     }
     ?>
    
  3. Displaying the error messages

    You can display error messages by printing the errors.

     <form action="" method="post" class="w-25 mx-auto" style="min-width: 300px;">
                 <div class="mb-3">
                     <!-- Name Input-->
                     <div class="text-danger fw-bold"><?php echo $nameError ?></div>
                 </div>
                 <div class="mb-3">
                     <!-- Email Input-->
                     <div class="text-danger fw-bold"><?php echo $emailError ?></div>
                 </div>
                 <div class="mb-3">
                     <!-- URL Input-->
                     <div class="text-danger fw-bold"><?php echo $urlError ?></div>
                 </div>
                 <div class="mb-3">
                     <!-- Password Input-->
                     <div class="text-danger fw-bold"><?php echo $passwordError ?></div>
                 </div>
     </form>
    

This should work but it does not. The code does not work because the page automatically refreshes once the submit button is clicked. This means that the error messages will be inaccessible.

To fix this, you will store the error messages in session variables.

<?php
session_start();
// validation functions

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    // Validating the user input

    if (isset($nameError)) {
        $_SESSION['nameError'] = $nameError;
    }
    if (isset($emailError)) {
        $_SESSION['emailError'] = $emailError;
    }
    if (isset($urlError)) {
        $_SESSION['urlError'] = $urlError;
    }
    if (isset($passwordError)) {
        $_SESSION['passwordError'] = $passwordError;
    }
}
?>
<form action="" method="post" class="w-25 mx-auto" style="min-width: 300px;">
            <div class="mb-3">
                <!-- Name Input-->
                <div class="text-danger fw-boldk"><?php echo $_SESSION['nameError'] ?></div>
            </div>
            <div class="mb-3">
                <!-- Email Input-->
                <div class="text-danger fw-bold"><?php echo $_SESSION['emailError'] ?></div>
            </div>
            <div class="mb-3">
                <!-- URL Input-->
                <div class="text-danger fw-bold"><?php echo $_SESSION['urlError'] ?></div>
            </div>
            <div class="mb-3">
                <!-- Password Input-->
                <div class="text-danger fw-bold"><?php echo $_SESSION['passwordError'] ?></div>
            </div>
</form>

Now you should be able to see the error messages.

However, you will be faced with another problem. When the page is initially loaded, you will get errors. For example,

To solve this, you should check whether the session variable exists before printing it.

<?php
session_start();
// validation functions

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    // Validating the user input

    if (isset($nameError)) {
        $_SESSION['nameError'] = $nameError;
    }
    if (isset($emailError)) {
        $_SESSION['emailError'] = $emailError;
    }
    if (isset($urlError)) {
        $_SESSION['urlError'] = $urlError;
    }
    if (isset($passwordError)) {
        $_SESSION['passwordError'] = $passwordError;
    }
}
?>
<form action="" method="post" class="w-25 mx-auto" style="min-width: 300px;">
            <div class="mb-3">
                <!-- Name Input-->
                <div class="text-danger fw-boldk"><?php echo isset($_SESSION['nameError']) ? $_SESSION['nameError'] : "" ?></div>
            </div>
            <div class="mb-3">
                <!-- Email Input-->
                <div class="text-danger fw-bold"><?php echo isset($_SESSION['emailError']) ? $_SESSION['emailError'] : "" ?></div>
            </div>
            <div class="mb-3">
                <!-- URL Input-->
                <div class="text-danger fw-bold"><?php echo isset($_SESSION['urlError']) ? $_SESSION['urlError'] : "" ?></div>
            </div>
            <div class="mb-3">
                <!-- Password Input-->
                <div class="text-danger fw-bold"><?php echo isset($_SESSION['passwordError']) ? $_SESSION['passwordError'] : "" ?></div>
            </div>
</form>

How to Retain the User Input

In this section, you will learn how to retain the user's inputs in the fields after they are validated.

You will use session variables to store the user's inputs and access them later.

<?php
    $formFields = [];
  // validating the name
    $formFields['name'] = $name;

    // validating the email
    $formFields['email'] = $email;

    //validating the URL
    $formFields['url'] = $url;

    // validating the password
    $formFields['password'] = $password;

    $_SESSION['formFields'] = $formFields;
?>

Assign the inputs with a value of the user's inputs.

<form action="" method="post" class="w-25 mx-auto" style="min-width: 300px;">
   <div class="mb-3">
      <input ... value="<?php echo isset($_SESSION['formFields']['name']) ? $_SESSION['formFields']['name'] : "" ?>">
   </div>
   <div class="mb-3">
      <input ... value="<?php echo isset($_SESSION['formFields']['email']) ? $_SESSION['formFields']['email'] : "" ?>">
   </div>
   <div class="mb-3">
       <input ... value="<?php echo isset($_SESSION['formFields']['url']) ? $_SESSION['formFields']['url'] : "" ?>">
   </div>
   <div class="mb-3">
       <input ... value="<?php echo isset($_SESSION['formFields']['password']) ? $_SESSION['formFields']['password'] : "" ?>">
   </div>

</form>

After submitting your form, you should see the output below:

Conclusion

In this article, you have learned how to:

  1. validate empty fields

  2. validate text

  3. validate emails

  4. validate URLs

  5. validate passwords

  6. display error messages

  7. retain the user's input in the form

You can find the source code for this tutorial here.