PHP Form Validation

Learn how to validate user input in PHP forms to ensure data integrity and security.

What is Form Validation?

Form validation is the process of checking user input from an HTML form to ensure that it meets specific criteria before processing or storing it. This helps prevent errors and security vulnerabilities such as SQL injection and cross-site scripting (XSS).

Why Validate Form Data?

  • Data Integrity: Ensure that the data submitted is accurate and formatted correctly.
  • Security: Prevent malicious input that could exploit vulnerabilities in your application.
  • User Experience: Provide immediate feedback to users about any issues with their input.

Basic Form Example

Here’s a simple HTML form for collecting a user’s name and email:

<form action="form-validation.php" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

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

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

Validating Form Data

Once the form is submitted, you can validate the input using PHP. Here's how to do it:

<?php
// Initialize variables to hold error messages
$nameErr = $emailErr = "";
$name = $email = "";

// Validate when the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate Name
    if (empty($_POST["name"])) {
        $nameErr = "Name is required.";
    } else {
        $name = htmlspecialchars(trim($_POST["name"]));
        // Check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
            $nameErr = "Only letters and white space allowed.";
        }
    }

    // Validate Email
    if (empty($_POST["email"])) {
        $emailErr = "Email is required.";
    } else {
        $email = htmlspecialchars(trim($_POST["email"]));
        // Check if the email address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format.";
        }
    }
}
?>

Displaying Validation Errors

You can display error messages back to the user as follows:

<?php
// Display the form and error messages
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!empty($nameErr)) {
        echo "<p class='text-red-500'>" . $nameErr . "</p>";
    }
    if (!empty($emailErr)) {
        echo "<p class='text-red-500'>" . $emailErr . "</p>";
    }
}
?>

Full Example

Here’s a complete example of a form with validation:

<?php
$nameErr = $emailErr = "";
$name = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required.";
    } else {
        $name = htmlspecialchars(trim($_POST["name"]));
        if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
            $nameErr = "Only letters and white space allowed.";
        }
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required.";
    } else {
        $email = htmlspecialchars(trim($_POST["email"]));
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format.";
        }
    }
}
?>

<form action="" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" value="<?php echo $name; ?>" required>
    <p class='text-red-500'><?php echo $nameErr; ?></p>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" value="<?php echo $email; ?>" required>
    <p class='text-red-500'><?php echo $emailErr; ?></p>

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

Conclusion

Validating form data in PHP is essential for ensuring data integrity, enhancing security, and improving user experience. Always validate user input to safeguard your application from malicious data and provide clear feedback to users.