Web Development Lesson 13 of 17
PHP Form Validation
Validate form input on the server — required fields, lengths, numbers, emails and PH mobile numbers with filter_var and preg_match — show error messages and keep what the user typed.
Never trust form data. Users make typos, leave fields empty, and attackers send data on purpose. Server-side validation in PHP checks everything before you save it. Browser checks (like the HTML required attribute) are helpful, but anyone can bypass them, so PHP must check again.
The validation pattern
- Read and clean each value (
trim). - Check it, and store a message in an
$errorsarray if it's wrong. - If
$errorsis empty, save the data. Otherwise, show the form again with the messages and the user's previous input.
A validation function
<?php
function validateRegistration(array $in): array {
$errors = [];
$name = trim($in["name"] ?? "");
$email = trim($in["email"] ?? "");
$mobile = trim($in["mobile"] ?? "");
$age = $in["age"] ?? "";
if ($name === "") {
$errors["name"] = "Name is required.";
} elseif (mb_strlen($name) < 2 || mb_strlen($name) > 60) {
$errors["name"] = "Name must be 2 to 60 characters.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "Enter a valid email address.";
}
if (!preg_match('/^09\d{9}$/', $mobile)) {
$errors["mobile"] = "Mobile number must be 11 digits starting with 09.";
}
$ageNum = filter_var($age, FILTER_VALIDATE_INT, ["options" => ["min_range" => 12, "max_range" => 25]]);
if ($ageNum === false) {
$errors["age"] = "Age must be a whole number from 12 to 25.";
}
return $errors;
}
print_r(validateRegistration([
"name" => "A", "email" => "ana@", "mobile" => "0917123", "age" => "30",
]));
print_r(validateRegistration([
"name" => "Ana Reyes", "email" => "ana@example.com", "mobile" => "09171234567", "age" => "16",
]));
Output
Array
(
[name] => Name must be 2 to 60 characters.
[email] => Enter a valid email address.
[mobile] => Mobile number must be 11 digits starting with 09.
[age] => Age must be a whole number from 12 to 25.
)
Array
(
)The first input has four problems; the second passes, so the errors array is empty.
Useful validation tools
| Check | Code |
|---|---|
| Not empty | trim($x) !== "" |
| Length | mb_strlen($x) <= 60 |
filter_var($x, FILTER_VALIDATE_EMAIL) | |
| Whole number in a range | filter_var($x, FILTER_VALIDATE_INT, ["options" => [...]]) |
| Decimal number | is_numeric($x) or FILTER_VALIDATE_FLOAT |
| URL | filter_var($x, FILTER_VALIDATE_URL) |
| Pattern | preg_match('/^09\d{9}$/', $x) |
| One of a list | in_array($x, ["STEM", "ABM"], true) |
preg_match uses regular expressions. /^09\d{9}$/ means: start, "09", exactly 9 digits, end.
Showing errors and keeping input
<?php
$errors = [];
$old = ["name" => "", "email" => ""];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$old = ["name" => trim($_POST["name"] ?? ""), "email" => trim($_POST["email"] ?? "")];
if ($old["name"] === "") $errors["name"] = "Name is required.";
if (!filter_var($old["email"], FILTER_VALIDATE_EMAIL)) $errors["email"] = "Invalid email.";
if (!$errors) {
// save to the database here, then redirect
header("Location: thanks.php");
exit;
}
}
function e(string $s): string { return htmlspecialchars($s, ENT_QUOTES, "UTF-8"); }
?>
<form method="post" novalidate>
<label>Name <input name="name" value="<?= e($old["name"]) ?>"></label>
<?php if (isset($errors["name"])): ?><p class="error"><?= e($errors["name"]) ?></p><?php endif; ?>
<label>Email <input name="email" value="<?= e($old["email"]) ?>"></label>
<?php if (isset($errors["email"])): ?><p class="error"><?= e($errors["email"]) ?></p><?php endif; ?>
<button>Register</button>
</form>
Putting the old values back into the inputs means the user only fixes the wrong field instead of retyping everything. After a successful save, redirect with header("Location: ..."). That prevents the form from being submitted twice if the user refreshes (the "Post/Redirect/Get" pattern).
Validation vs escaping vs prepared statements
- Validate input to make sure it makes sense (this lesson).
- Escape output with
htmlspecialcharsto prevent XSS (previous lesson). - Use prepared statements for database queries to prevent SQL injection (PDO lesson).
You need all three; one doesn't replace another.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04