When processing web forms, applications must enforce required field rules, preserve valid user inputs across form resubmissions, and display clear inline error messages to the user.
flowchart TD
A["Form Submitted"] --> B["Iterate Required Fields"]
B --> C{"Is Field Empty?"}
C -- Yes --> D["Append Field Error Message"]
C -- No --> E["Sanitize & Store In $validData"]
D & E --> F{"Has Any Errors?"}
F -- Yes --> G["Re-render Form with Preserved Values & Inline Errors"]
F -- No --> H["Execute Success Action / Redirect"]
<?php
declare(strict_types=1);
$errors = [];
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate Required Name
if (empty($_POST["name"])) {
$errors["name"] = "Name is required";
} else {
$name = htmlspecialchars(trim($_POST["name"]));
}
// Validate Required Email
if (empty($_POST["email"])) {
$errors["email"] = "Email is required";
} else {
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Required Field Form</title>
<style>
.error { color: #ef4444; font-size: 0.875rem; }
.input-group { margin-bottom: 1rem; }
</style>
</head>
<body style="font-family: system-ui, sans-serif; background: #0f172a; color: #f8fafc; padding: 2rem;">
<form method="post" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="input-group">
<label>Name (*):</label><br>
<input type="text" name="name" value="<?= $name; ?>">
<span class="error"><?= $errors["name"] ?? ""; ?></span>
</div>
<div class="input-group">
<label>Email (*):</label><br>
<input type="text" name="email" value="<?= $email; ?>">
<span class="error"><?= $errors["email"] ?? ""; ?></span>
</div>
<button type="submit">Submit Registration</button>
</form>
</body>
</html>
$name and $email back into HTML value="" attributes so users don't have to retype valid fields after a single field fails validation.$_SERVER["PHP_SELF"] Safely: Always wrap $_SERVER["PHP_SELF"] inside htmlspecialchars() to prevent XSS form action exploits.(*) or labels.Write an if (empty($_POST['username'])) check that sets $errors['username'] = "Username is required" when the input is blank!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.