PHP Form Validation
Form validation is the step where you confirm that submitted data is present, correctly formatted, and safe before your application acts on it.
Why validation matters
Validation answers a simple question: is this input actually what I asked for? A registration form expects a real email address, a non-empty name, and perhaps an age within a sensible range. Without checking, your code might store nonsense, crash on unexpected values, or become a security hole. Browser-side validation with HTML attributes improves the experience, but it can be bypassed easily, so the checks that count must always run on the server in PHP.
It helps to separate two related ideas. Sanitising cleans a value, for example stripping stray tags or trimming spaces. Validating judges a value, for example confirming it matches the shape of an email address. Good forms usually do both.
Required fields and error collection
A dependable approach is to gather all errors into an array while you check each field, rather than stopping at the first problem. If the array is empty at the end, the form is valid; otherwise you redisplay it and show every message at once.
Validating required fields
<?php
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
if ($name === '') {
$errors['name'] = 'Please enter your name.';
}
if ($email === '') {
$errors['email'] = 'Please enter your email.';
}
if (empty($errors)) {
echo 'All good, saving the record.';
}
}
foreach ($errors as $message) {
echo '<p style="color:red">' . htmlspecialchars($message) . '</p>';
}
?>Using the built-in filter functions
PHP ships with filter_var, which validates and sanitises common formats without you writing fragile patterns by hand. It covers emails, URLs, integers, floats, and more, and it returns false when the value does not pass.
Validating an email and an integer
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = trim($_POST['email'] ?? '');
$age = $_POST['age'] ?? '';
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo 'That does not look like a valid email address.<br>';
}
$ageValue = filter_var($age, FILTER_VALIDATE_INT,
['options' => ['min_range' => 13, 'max_range' => 120]]);
if ($ageValue === false) {
echo 'Please enter an age between 13 and 120.';
}
}
?>Common validation rules
- Required: the field must not be empty after trimming
- Format: emails, URLs, and dates must match their expected shape
- Range: numbers should fall within sensible minimum and maximum bounds
- Length: limit text fields so overly long input cannot cause problems
- Allowed values: dropdowns and radios should match a known list you define