PHP Form Validation (Advanced)

What Is Form Validation?

Form validation is the process of ensuring that the data submitted by users is:

  • Complete
  • Correct (format, type, range)
  • Safe to store or process

Client-side vs Server-side Validation:

TypeDescription
Client-sideDone in browser using HTML/JavaScript
Server-sideDone in PHP after submission (required for security)

Always use server-side validation, even if client-side validation exists — users can bypass client scripts.

Basic Server-Side Validation in PHP

Let’s revisit a simple form and add thorough validation.

📄 HTML Form (form.html)

HTML
<form action="validate.php" method="post">
  Name: <input type="text" name="name"><br>
  Email: <input type="text" name="email"><br>
  Age: <input type="number" name="age"><br>
  <input type="submit" value="Submit">
</form>

Validating and Sanitizing Inputs in PHP

📄 validate.php

PHP
<?php
function sanitize($data) {
  return htmlspecialchars(trim($data));
}

$errors = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = sanitize($_POST['name']);
  $email = sanitize($_POST['email']);
  $age = sanitize($_POST['age']);

  // Name validation
  if (empty($name)) {
    $errors[] = "Name is required";
  } elseif (!preg_match("/^[a-zA-Z ]*$/", $name)) {
    $errors[] = "Name must contain only letters and spaces";
  }

  // Email validation
  if (empty($email)) {
    $errors[] = "Email is required";
  } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Invalid email format";
  }

  // Age validation
  if (empty($age)) {
    $errors[] = "Age is required";
  } elseif (!filter_var($age, FILTER_VALIDATE_INT)) {
    $errors[] = "Age must be a valid number";
  }

  // Display results
  if (!empty($errors)) {
    foreach ($errors as $err) {
      echo "<p style='color:red;'>$err</p>";
    }
  } else {
    echo "<p style='color:green;'>Validation successful!</p>";
    echo "Name: $name <br>Email: $email <br>Age: $age";
  }
}
?>

Using Regular Expressions in PHP

PHP’s preg_match() function allows advanced validation using patterns.

Validate Phone Number (Indian Format):

PHP
$phone = "9876543210";
if (!preg_match("/^[6-9][0-9]{9}$/", $phone)) {
  echo "Invalid phone number";
}

Validate Username:

PHP
$username = "script_buzz_123";
if (!preg_match("/^[a-zA-Z0-9_]{5,15}$/", $username)) {
  echo "Username must be 5–15 characters long and can include underscores";
}

Real-World Example: Contact Form with Advanced Validation

📄 contact.html

HTML
<form action="submit.php" method="post">
  Name: <input type="text" name="name"><br>
  Email: <input type="email" name="email"><br>
  Subject: <input type="text" name="subject"><br>
  Message: <textarea name="message"></textarea><br>
  <input type="submit" value="Send">
</form>

📄 submit.php

PHP
<?php
function clean($input) {
  return htmlspecialchars(trim($input));
}

$errors = [];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $name = clean($_POST['name']);
  $email = clean($_POST['email']);
  $subject = clean($_POST['subject']);
  $message = clean($_POST['message']);

  // Validate all fields
  if (!$name || !preg_match("/^[a-zA-Z ]+$/", $name)) {
    $errors[] = "Valid name required";
  }
  if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Valid email required";
  }
  if (!$subject || strlen($subject) < 5) {
    $errors[] = "Subject must be at least 5 characters";
  }
  if (!$message || strlen($message) < 10) {
    $errors[] = "Message must be at least 10 characters";
  }

  if (!empty($errors)) {
    foreach ($errors as $error) {
      echo "<p style='color:red;'>$error</p>";
    }
  } else {
    echo "<p style='color:green;'>Thank you for your message, $name!</p>";
    // Here you could also send an email or save to DB
  }
}
?>

Preventing Common Security Issues

  • Cross-Site Scripting (XSS)
    • Always use htmlspecialchars() on user output
  • Header Injection
    • Sanitize inputs in headers (e.g., email)
  • ✅ Always validate on server-side even if client-side validation is used

Best Practices

  • Validate all input types: text, number, email, checkboxes, radios
  • Use trim() to remove unnecessary spaces
  • Use htmlspecialchars() to prevent HTML injection
  • Create reusable validation functions
  • Group errors and display them clearly for the user
  • Use regex for advanced formats (emails, usernames, phone numbers)

Common Mistakes to Avoid

  • Relying only on client-side validation
  • Not trimming or cleaning data before storing
  • Using incorrect regex patterns
  • Forgetting to handle form resubmission (e.g., with redirects)
  • Not checking for empty values with isset() or empty()

Notes:

  • Form validation ensures clean, safe, and expected user input
  • Use filter_var() for common validations and preg_match() for custom patterns
  • Always sanitize input with htmlspecialchars() or similar methods
  • Display errors clearly and avoid crashing the page
  • Proper validation is essential for both security and user experience

Practice Tasks

Task 1: Registration Form
Create a form with:

  • Name
  • Email
  • Username (5–15 characters, no special characters)
  • Password (min. 6 chars)
    Validate all fields using PHP.

Task 2: Feedback Validator
Create a feedback form that:

  • Requires message to be minimum 50 characters
  • Validates subject with a regex to accept only letters and spaces
  • Sanitizes and shows success or error

Task 3: Smart Form Handler
Create a reusable function validateField($input, $type) that handles different validation types like email, int, alpha, etc.