Required, URL/Email Validation & Complete Form
Use HTML required attribute for quick feedback, but always re-check on the server with empty() or trim() === "".
Required Fields
Use HTML required attribute for quick feedback, but always re-check on the server with empty() or trim() === "".
Real-life example: Required fields are mandatory questions on an exam — blank answers mean no pass.
<?php
function required(string $value, string $label): ?string {
if (trim($value) === "") {
return "$label is required.";
}
return null;
}
$error = required($_POST["course"] ?? "", "Course name");
echo $error ?? "OK";
?>Validate URL and Email
filter_var() with FILTER_VALIDATE_EMAIL and FILTER_VALIDATE_URL is the safest easy check for common formats.
Real-life example: Email validation is checking if an address looks like a real mailbox, not random keyboard smashes.
<?php
$email = "asha@knowvora.com";
$url = "https://knowvora.com";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email";
}
if (!filter_var($url, FILTER_VALIDATE_URL)) {
echo "Invalid URL";
}
?>Complete Form Example
A complete form shows errors, keeps old values, and escapes output with htmlspecialchars() to prevent XSS attacks.
Real-life example: A complete form is a polite reception desk — it tells you what went wrong and remembers what you already typed.
<?php
$name = $email = $message = "";
$errors = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$message = trim($_POST["message"] ?? "");
if ($name === "") $errors[] = "Name required.";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email required.";
if ($message === "") $errors[] = "Message required.";
if (!$errors) {
echo "<p>Thanks, " . htmlspecialchars($name) . "! We will reply soon.</p>";
}
}
?>
<form method="post">
<input name="name" value="<?= htmlspecialchars($name) ?>" placeholder="Name" />
<input name="email" value="<?= htmlspecialchars($email) ?>" placeholder="Email" />
<textarea name="message"><?= htmlspecialchars($message) ?></textarea>
<button type="submit">Send</button>
</form>
<?php foreach ($errors as $e): ?>
<p style="color:red"><?= htmlspecialchars($e) ?></p>
<?php endforeach; ?>