codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐘

PHP

34 / 56 topics
33Forms in PHP34Form Validation
Tutorials/PHP/Form Validation
🐘PHP

Form Validation

Updated 2026-05-15
10 min read

Form Validation

Introduction

In web development, form validation is a crucial step to ensure that the data collected from users meets specific criteria before it's processed or stored. This tutorial will guide you through the process of validating user input from forms in PHP. We'll cover both client-side and server-side validation, providing practical examples to help you understand how to implement these techniques effectively.

Concept

Form validation can be performed on both the client side (using JavaScript) and the server side (using PHP). Client-side validation provides immediate feedback to users and reduces unnecessary server requests, but it can be bypassed by malicious users. Therefore, server-side validation is essential to ensure data integrity and security.

Client-Side Validation

Client-side validation is typically done using JavaScript. It involves checking user input before the form is submitted. This can include checks for required fields, valid email formats, numeric values, etc. While client-side validation enhances user experience, it should not be relied upon solely for security reasons.

Server-Side Validation

Server-side validation is performed on the server after the form data has been sent by the client. It ensures that the data adheres to the required rules and constraints before processing or storing it. This step is crucial for maintaining data integrity and preventing malicious input.

Examples

Let's walk through a practical example of validating user input from a form using PHP.

Step 1: Create an HTML Form

First, create an HTML form that collects user input. We'll include basic client-side validation using JavaScript.

<!DOCTYPE html>
<html lang="en">
&lt;head&gt;
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title&gt;Form Validation</title>
    &lt;script&gt;
        function validateForm() {
            const email = document.forms["myForm"]["email"].value;
            if (email === "") {
                alert("Email must be filled out");
                return false;
            }
            const atPosition = email.indexOf("@");
            const dotPosition = email.lastIndexOf(".");
            if (atPosition < 1 || dotPosition < atPosition + 2 || dotPosition + 2 >= email.length) {
                alert("Please enter a valid e-mail address");
                return false;
            }
        }
    </script>
</head>
&lt;body&gt;
    <form name="myForm" action="validate.php" onsubmit="return validateForm()" method="post">
        Email: <input type="text" name="email"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Step 2: Create the PHP Validation Script

Next, create a PHP script (validate.php) to handle server-side validation.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect and sanitize input data
    $email = htmlspecialchars($_POST['email']);

    // Validate email format using PHP's filter_var function
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<p style='color:red;'>Invalid email format.</p>";
    } else {
        echo "<p style='color:green;'>Email is valid.</p>";
    }
}
?>

Explanation

  1. HTML Form: The form includes a simple JavaScript function validateForm() that checks if the email field is empty and if it contains a valid email format. If validation fails, an alert is shown, and the form submission is prevented.

  2. PHP Validation Script:

    • The script checks if the request method is POST.
    • It collects the email input using $_POST and sanitizes it using htmlspecialchars() to prevent XSS attacks.
    • It uses PHP's filter_var() function with FILTER_VALIDATE_EMAIL to validate the email format.
    • Depending on the validation result, it outputs a message indicating whether the email is valid or not.

What's Next?

Now that you have learned about form validation in PHP, the next step is to explore sessions. Sessions allow you to store user-specific data across multiple pages of your application, which is essential for maintaining user state and managing logged-in users.

Stay tuned for more tutorials on advanced PHP topics!


PreviousForms in PHPNext Sessions in PHP

Recommended Gear

Forms in PHPSessions in PHP