Post Date: January 09, 2019
Last Updated: October 04, 2026
Introduction
Form validation is an essential part of web development. It ensures that users enter valid and complete information before submitting a form.
PHP allows developers to validate form data on the server side, helping prevent invalid submissions and improving data integrity.
In this tutorial, we’ll create a simple HTML form and use PHP to validate text fields, email addresses, radio buttons, checkboxes, and multiple selections.
Prerequisites
Before getting started, ensure you have:
- Basic knowledge of HTML and PHP.
- PHP installed on your system or access to a PHP-enabled web server.
- A code editor such as Visual Studio Code.
- Basic understanding of HTML forms and HTTP POST requests.
Implementation
Step 1: Create an HTML Form
First, create an HTML form with fields for name, address, email, a radio selection, favorite fruits, and a brochure checkbox.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Form Validation</title>
</head>
<body>
<h2>Registration Form</h2>
<form method="POST" action="">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br><br>
<label for="address">Address:</label>
<input type="text" id="address" name="address">
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<br><br>
<p>How many people are attending?</p>
<label><input type="radio" name="howMany" value="zero"> 0</label>
<label><input type="radio" name="howMany" value="one"> 1</label>
<label><input type="radio" name="howMany" value="two"> 2</label>
<label><input type="radio" name="howMany" value="twoplus"> More than 2</label>
<p>Select your favorite fruits:</p>
<select name="favFruit[]" size="4" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="plum">Plum</option>
<option value="pomegranate">Pomegranate</option>
<option value="strawberry">Strawberry</option>
<option value="watermelon">Watermelon</option>
</select>
<p>
<label>
<input type="checkbox" name="brochure" value="Yes">
Send me a brochure
</label>
</p>
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
This form uses the POST method to send user input to the server. The favFruit[] name allows multiple fruit selections to be submitted as an array.
Step 2: Validate Form Data Using PHP
Add the following PHP code at the beginning of your PHP file, before the HTML output.
<?php
$nameErr = $addrErr = $emailErr = "";
$howManyErr = $favFruitErr = "";
$name = $address = $email = "";
$howMany = "";
$favFruit = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Validate name
$name = trim($_POST["name"] ?? "");
if ($name === "") {
$nameErr = "Name is required.";
}
// Validate address
$address = trim($_POST["address"] ?? "");
if ($address === "") {
$addrErr = "Address is required.";
}
// Validate email
$email = trim($_POST["email"] ?? "");
if ($email === "") {
$emailErr = "Email is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Enter a valid email address.";
}
// Validate radio selection
$allowedOptions = ["zero", "one", "two", "twoplus"];
$howMany = $_POST["howMany"] ?? "";
if (!in_array($howMany, $allowedOptions, true)) {
$howManyErr = "Please select one option.";
}
// Validate fruit selection
$allowedFruits = [
"apple", "banana", "plum",
"pomegranate", "strawberry", "watermelon"
];
$submittedFruits = $_POST["favFruit"] ?? [];
if (!is_array($submittedFruits)) {
$submittedFruits = [];
}
$favFruit = array_values(array_intersect(
$submittedFruits,
$allowedFruits
));
if (empty($favFruit)) {
$favFruitErr = "Please select at least one fruit.";
}
// Check brochure selection
$brochure = isset($_POST["brochure"]) &&
$_POST["brochure"] === "Yes";
}
?>
Explanation
trim()removes unnecessary whitespace from text input.filter_var()checks whether the email address has a valid format.in_array()verifies that the radio selection matches an allowed value.array_intersect()filters fruit selections against the permitted options.isset()checks whether the optional brochure checkbox was selected.
These checks validate submitted data on the server, even if browser-side validation is bypassed.
Step 3: Display Validation Errors
To make the form user-friendly, display validation messages next to the corresponding fields.
For example, update the name and email fields in your HTML form as follows:
<label for="name">Name:</label>
<input
type="text"
id="name"
name="name"
value="<?= htmlspecialchars($name) ?>"
>
<span><?= htmlspecialchars($nameErr) ?></span>
<br><br>
<label for="email">Email:</label>
<input
type="email"
id="email"
name="email"
value="<?= htmlspecialchars($email) ?>"
>
<span><?= htmlspecialchars($emailErr) ?></span>
You can display the remaining validation messages in the same way:
<span><?= htmlspecialchars($addrErr) ?></span> <span><?= htmlspecialchars($howManyErr) ?></span> <span><?= htmlspecialchars($favFruitErr) ?></span>
Using htmlspecialchars() helps prevent user-submitted content from being interpreted as HTML when displayed.
Step 4: Process Validated Form Data
Once all required fields pass validation, you can process the submitted data.
<?php
if (
$_SERVER["REQUEST_METHOD"] === "POST" &&
$nameErr === "" &&
$addrErr === "" &&
$emailErr === "" &&
$howManyErr === "" &&
$favFruitErr === ""
) {
echo "Form submitted successfully!";
}
?>
In a real application, you can replace the success message with your database insertion or other processing logic. Always use prepared statements when storing user input in a database.
Official PHP Documentation
For more information about PHP form validation, input filtering, and securely displaying user-submitted data, refer to the official PHP documentation:
– PHP: Data Filtering – Learn how to validate and sanitize input data using PHP’s filtering functions.
– PHP: filter_var() – Understand how to validate data, including email addresses, using built-in PHP filters.
Conclusion
PHP form validation helps ensure that submitted information is complete, correctly formatted, and suitable for further processing. By combining HTML forms with PHP validation functions, developers can create more reliable and secure web applications.
Server-side validation should always be implemented, even when browser-side validation is enabled, because client-side checks can be bypassed.
FAQs
1. What is form validation in PHP?
Form validation in PHP is the process of checking user-submitted data on the server to ensure that it meets the required conditions before processing or storing it.
2. How do you validate an email address in PHP?
You can use filter_var() with FILTER_VALIDATE_EMAIL to check whether an email address has a valid format.
3. What is the difference between client-side and server-side validation?
Client-side validation runs in the user’s browser and provides immediate feedback. Server-side validation runs on the web server and is essential for security and data integrity.
Related Articles
Talk to Our Experts
Need help building secure PHP forms or improving your web application? Our experts can help you develop reliable and efficient web solutions.
Get in touch with us: Contact our team.