HTMLJavaScriptphp

PHP Form Validation with code and example

Below, I’ll provide a comprehensive guide on PHP form validation, including code examples, best practices, and explanations for each part. we will validate a simple contact form with three fields: name, email, and message.

PHP Form Validation Guide

1. Basic Form Structure

First, let’s create a simple HTML form that we will validate. This form will collect a user’s name and email address.

<?php
// define variables and set to empty values
$name = $email = $message = "";
$nameErr = $emailErr = $messageErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed";
    }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if email address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
    }
  }
    
  if (empty($_POST["message"])) {
    $messageErr = "Message is required";
  } else {
    $message = test_input($_POST["message"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  Name: <input type="text" name="name">
  <span class="error">* <?php echo $nameErr;?></span>
  <br><br>
  Email: <input type="text" name="email">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
  Message: <textarea name="message" rows="5" cols="40"></textarea>
  <span class="error">* <?php echo $messageErr;?></span>
  <br><br>
  <input type="submit" name="submit" value="Submit">  
</form>

In this code, we first define the variables and set them to empty values. We also define error variables for each field. Then, we check if the form has been submitted (using $_SERVER["REQUEST_METHOD"] == "POST") and if so, we validate each field.

For each field, we first check if it is empty. If it is, we set the corresponding error variable. If it is not empty, we use the test_input() function to sanitize the input and then we perform additional validation. For example, we use preg_match() to check if the name only contains letters and whitespace, and we use filter_var() with the FILTER_VALIDATE_EMAIL filter to check if the email address is well-formed.

Error Handling and User Feedback

The form includes error messages that are displayed next to the respective fields if validation fails. This provides immediate feedback to the user about what needs to be corrected.

Finally, we display the form with the corresponding error messages (using the <?php echo $nameErr;?> syntax) and we submit the form to the same page ($_SERVER["PHP_SELF"]) for processing.

Note that in this example, we are using the htmlspecialchars() function to prevent XSS attacks by converting special characters to their HTML entities.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button