Validation ensures submitted data meets the requirements of your application before you process or store it. Always validate on the server side — client-side (JavaScript) validation is a UX convenience, not a security measure.
Check that required fields are not empty.
Validate data types and ranges (e.g., age must be a number between 0 and 120).
Validate formats (e.g., email, URL, phone).
Return meaningful error messages to the user.
Example
<?php
$errors = [];
$values = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Required field
$name = trim($_POST['name'] ?? '');
if ($name === '') {
$errors['name'] = 'Name is required.';
} elseif (strlen($name) < 2) {
$errors['name'] = 'Name must be at least 2 characters.';
} else {
$values['name'] = $name;
}
// Email validation
$email = trim($_POST['email'] ?? '');
if ($email === '') {
$errors['email'] = 'Email is required.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Please enter a valid email address.';
} else {
$values['email'] = $email;
}
// Numeric range
$age = $_POST['age'] ?? '';
if (!is_numeric($age) || $age < 18 || $age > 120) {
$errors['age'] = 'Age must be a number between 18 and 120.';
} else {
$values['age'] = (int) $age;
}
if (empty($errors)) {
// All valid — process the form
echo 'Form submitted successfully!';
}
}
Pro Tip
Tip: Collect all validation errors before displaying them to the user. Showing one error at a time forces users to submit the form repeatedly — collect everything in an $errors array and display it all at once.