Form Validation in PHP with Examples

Form validation in PHP means checking all the fields of an HTML form to ensure they are filled out correctly before submitting the data to the server. This includes validating the following aspects:

  • Required fields
  • Email format
  • Numeric input
  • Password strength
  • Website URL
  • User selection fields such as checkboxes, radio buttons, and dropdowns
  • Filtering and sanitizing data

Form validation is one of the most important steps in developing a secure and user-friendly web application. It ensures that the data submitted by users meets specific criteria before being processed or stored.

This not only improves data quality but also protects your application from malicious attacks. Proper form validation enhances security, maintains data integrity, and provides a better user experience by preventing incorrect or incomplete submissions.

Types of Form Validation in PHP


In PHP, there are mainly two types of form validation:

  • Client-side validation
  • Server-side validation

What is Client-side Validation?


Client-side validation is the process of verifying user input in the browser before the form data is sent to the web server. It is performed using:

  • HTML5 form validation attributes
  • JavaScript

This type of validation provides instant responses to users and helps to correct mistakes before sending data to the web server.

Why Client-side Validation is Important?


Here are some important benefits and features of performing client-side validation:

  • Users get immediate feedback or responses when they enter incorrect data without waiting for the page to reload.
  • Since invalid data entered by the user is filtered out before form submission, fewer invalid requests reach the web server. Thus, it reduces server load.
  • The form feels more responsive and interactive when errors are shown in real time. Client-side validation provides better user experience.
  • Modern HTML5 provides various built-in attributes such as required, type, pattern, min, max, etc., making validation easy without JavaScript.

Note: Users can bypass client-side validation by disabling JavaScript or editing browser code. So, you should always use server-side validation as a backup.

Client-side Form Validation using HTML5 and JavaScript

Let’s take an example in which we will validate an HTML form in the client-side using HTML5 and JavaScript. Look at the below code.

<!DOCTYPE html>
<html>
<head>
    <title>Client-side Form Validation</title>
<script>
function validateForm() {
   let name = document.forms["myForm"]["name"].value.trim();
   let age = document.forms["myForm"]["age"].value;
   let password = document.forms["myForm"]["password"].value;

   if (name.length < 3) {
      alert("Name must be at least 3 characters long.");
      return false;
   }
   if (age < 18 || isNaN(age)) {
      alert("Age must be a number and at least 18.");
      return false;
   }
   if (password.length < 6) {
      alert("Password must be at least 6 characters.");
      return false;
   }

   return true; // This statement allows form submission.
}
</script>
</head>
<body>
<p style="font-size: 20px;"><strong>Registration Form (Client-side Validation)</strong></p>

<form name="myForm" onsubmit="return validateForm()" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required><br><br>

<label for="email">Email:</label>
<input type="email" name="email" id="email" required><br><br>

<label for="age">Age:</label>
<input type="number" name="age" id="age" required min="18"><br><br>

<label for="password">Password:</label>
<input type="password" name="password" id="password" required minlength="6"><br><br>

<label for="website">Website:</label>
<input type="url" name="website" id="website"><br><br>

<input type="submit" value="Submit">
</form>
</body>
</html>

When you render this code, a registration form will appear in the browser. If you enter incorrect data, the HTML5 attributes will provide instant feedback about the errors.

HTML5 attributes such as required, type, min, and minlength handle basic validation automatically. The JavaScript function validateForm() performs custom checks, such as verifying the minimum length of the name and the strength of the password. If any validation fails, an alert message is displayed, and the form is not submitted.

What is Server-side Validation?


Server-side validation is the process of checking and verifying the input from an HTML form after the data is submitted to the server. We can usually do it using a backend language like PHP to ensure that the submitted data is safe, complete, and valid before it is processed or stored in a database.

Unlike client-side validation, which occurs in the browser and can be bypassed by disabling JavaScript or modifying the code, server-side validation cannot be easily bypassed. It is an essential step to ensure security, data integrity, and protection against malicious inputs.

Why Server-side Validation Is Important?


Server-side validation is very important because it makes sure the data entered by users is safe, correct, and complete before it is used or stored. Here’s why it matters:

  • Server-side validation provides security. It protected your website from hackers, bots, and harmful input like scripts or fake data.
  • This type of validation checks data accuracy to ensure that users have entered the right kind of information, like a valid email or number, before saving it. This prevents wrong or incomplete data from entering your database.
  • The user can turn client-side validation off, but server-side validation happens on the server, so it can’t be bypassed.
  • Server-side validation also cleans the data by removing unwanted or dangerous characters like HTML tags or SQL commands.
  • It allows you to create custom rules, like checking if an email is already in use or if the password is strong enough, etc.

How to Perform Full Form Validation in PHP


Let’s take an example in which we will validate the following fields in a single form on the server-side using PHP language:

  • Name (text, required)
  • Email (valid format)
  • Age (numeric)
  • Password (min 6 characters)
  • Gender (radio button)
  • Hobbies (checkboxes)
  • Country (dropdown)

Follow the following steps one by one.

Step 1: Create an HTML form and save it form.html.

<!DOCTYPE html>
<html>
<head>
    <title>PHP Form Validation Example</title>
<style>
body {
   font-family: Arial;
   padding: 20px;
   background-color: #f2f2f2;
}
form {
   background-color: #fff;
   padding: 25px;
   border-radius: 8px;
   box-shadow: 0 0 10px #ccc;
   max-width: 500px;
   margin: auto;
}
label {
   font-weight: bold;
   display: inline-block;
   margin-bottom: 5px;
}
input, select {
   width: 100%;
   padding: 8px;
   margin-bottom: 15px;
   border-radius: 4px;
   border: 1px solid #ccc;
}
input[type="radio"],
input[type="checkbox"] {
   width: auto;
}
.form-group {
   margin-bottom: 15px;
}
.form-section {
   margin-bottom: 20px;
}
</style>
</head>
<body>
<p style="font-size: 22px;">Registration Form</p>
<form method="post" action="formvalidation.php">

<div class="form-group">
   <label for="name">Name:</label>
   <input type="text" name="name" id="name">
</div>

<div class="form-group">
   <label for="email">Email:</label>
   <input type="text" name="email" id="email">
</div>

<div class="form-group">
   <label for="age">Age:</label>
   <input type="text" name="age" id="age">
</div>

<div class="form-group">
   <label for="password">Password:</label>
   <input type="password" name="password" id="password">
</div>

<div class="form-section">
   <label>Gender:</label><br>
   <input type="radio" name="gender" value="Male" id="male">
   <label for="male">Male</label>
   <input type="radio" name="gender" value="Female" id="female">
   <label for="female">Female</label>
</div>

<div class="form-section">
   <label>Hobbies:</label><br>
   <input type="checkbox" name="hobbies[]" value="Reading" id="reading">
   <label for="reading">Reading</label><br>
   <input type="checkbox" name="hobbies[]" value="Coding" id="coding">
   <label for="coding">Coding</label><br>
   <input type="checkbox" name="hobbies[]" value="Traveling" id="traveling">
   <label for="traveling">Traveling</label>
</div>

<div class="form-group">
   <label for="country">Country:</label>
   <select name="country" id="country">
      <option value="">Select</option>
      <option value="India">India</option>
      <option value="USA">USA</option>
   </select>
</div>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

Step 2: Create a PHP script to process HTML form and save it with formvalidatation.php.

<?php
$name = $email = $age = $password = $gender = $country = "";
$hobbies = [];
$errors = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
 // Name Validation
   if (empty($_POST["name"])) {
       $errors[] = "Name is required";
   } else {
       $name = trim($_POST["name"]);
       if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
           $errors[] = "Only letters and spaces allowed in name";
       }
   }

 // Email Validation
   if (empty($_POST["email"])) {
       $errors[] = "Email is required";
   } else {
       $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
       if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $errors[] = "Invalid email format";
       }
   }

 // Age Validation
   if (empty($_POST["age"])) {
       $errors[] = "Age is required";
   } else {
       $age = filter_var($_POST["age"], FILTER_SANITIZE_NUMBER_INT);
       if (!filter_var($age, FILTER_VALIDATE_INT)) {
           $errors[] = "Age must be a number";
       }
   }

 // Password Validation
   if (empty($_POST["password"])) {
       $errors[] = "Password is required";
   } else {
       $password = trim($_POST["password"]);
       if (strlen($password) < 6) {
          $errors[] = "Password must be at least 6 characters";
       }
   }

 // Gender Validation
   if (empty($_POST["gender"])) {
       $errors[] = "Gender is required";
   } else {
       $gender = $_POST["gender"];
   }

 // Hobbies Validation
   if (!empty($_POST["hobbies"])) {
       $hobbies = $_POST["hobbies"];
   }

 // Country Validation
   if (empty($_POST["country"])) {
        $errors[] = "Please select a country";
   } else {
        $country = $_POST["country"];
   }

// Final Result
   if (empty($errors)) {
      echo "<h3>Form Submitted Successfully!</h3>";
      echo "Name: $name <br>";
      echo "Email: $email <br>";
      echo "Age: $age <br>";
      echo "Gender: $gender <br>";
      echo "Hobbies: " . implode(", ", $hobbies) . "<br>";
      echo "Country: $country <br>";
   } else {
       echo "<h3>Please fix the following errors:</h3>";
       echo "<ul>";
       foreach ($errors as $error) {
          echo "<li>$error</li>";
       }
      echo "</ul>";
   }
}
?>

Explanation of PHP Code:

In the above PHP code, we have created empty string variables and empty array variables. The variable $errors is an array that will store any validation error messages.

The line if ($_SERVER[“REQUEST_METHOD”] == “POST”) checks that if the form was submitted using the POST method. The empty($_POST[“name”]) checks that if the name field is empty. If yes, it adds an error message. The trim() function removes extra white spaces. The preg_match() function checks that if the name contains only letters and spaces.

The empty($_POST[“email”]) function checks if the email field is left blank. If not empty, the trim() function removes extra spaces. FILTER_SANITIZE_EMAIL is a filter used to clean up email addresses by removing illegal or unwanted characters from the input string.

Its purpose is to sanitize (clean) an email input before validating it using FILTER_VALIDATE_EMAIL. After that, FILTER_VALIDATE_EMAIL checks whether the email format is valid or not. If it’s invalid, an error message is added to the $errors array variable.

FILTER_SANITIZE_NUMBER_INT is a filter in PHP which removes anything that is not a number. The PHP filter FILTER_VALIDATE_INT confirms that the age is a valid integer (whole number). If it’s not a number, an error message is added to $errors array variable.

Thus, if there are no validation errors (i.e., $errors array is empty), it means that the form is filled correctly. If the form is filled out correctly, the user will see their submitted information displayed on the browser like this:

Output:
    Form Submitted Successfully!
    Name: John Doe
    Email: johndoe@example.com
    Age: 25
    Gender: Male
    Hobbies: Reading, Coding
    Country: India

Best Practices for Form Validation in PHP


You should use both client-side and server-side validation because they provide a double layer of protection and a better user experience. Here, we have listed some important points about form validation in PHP that you should keep in mind.

  • Always perform client-side validation, which immediately helps users correct errors instantly with no need to reload the page.
  • This also reduces unnecessary server requests. But remember, users can bypass this, so server-side validation is still necessary.
  • Always sanitize user input filter_var() and htmlspecialchars() before processing or storing. This protects your site from malicious input.
  • Use POST method to keep sensitive data secure.
  • Always validate all input fields on the server side, even if client-side checks exist. This is because server-side validation is secure and reliable.
  • Display clear error messages so that users know what’s wrong and how to fix it.
  • If you want to save passwords to a database, store them securely using hashing.
  • Always maintain entered form data when showing validation errors.

These are the best practices for form validation in PHP that will keep your form page secure. You can confidently follow and implement them in any web project to ensure data safety and a better user experience. In the next tutorial, we will learn how to validate login form and submit it to the database.