PHP Form Validation
Validation = "does the data look right?". Run it server-side; never trust client checks alone. Use PHP's filter_var() for common shapes, custom rules for the rest.
The pattern
PHP
$errors = [];
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$url = trim($_POST['url'] ?? '');
if ($name === '') {
$errors['name'] = 'Name is required';
} elseif (strlen($name) > 80) {
$errors['name'] = 'Name must be 80 characters or less';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Invalid email';
}
if ($url !== '' && !filter_var($url, FILTER_VALIDATE_URL)) {
$errors['url'] = 'Invalid URL';
}
if (empty($errors)) {
// save and redirect
} else {
// re-render form with errors
}
filter_var validators
| Filter | Validates |
|---|---|
FILTER_VALIDATE_EMAIL | RFC-5321 email shape. |
FILTER_VALIDATE_URL | URL with scheme. |
FILTER_VALIDATE_INT | Integer string. |
FILTER_VALIDATE_FLOAT | Float string. |
FILTER_VALIDATE_BOOL | "true"/"false"/"on"/etc. |
FILTER_VALIDATE_IP | IPv4 / IPv6. |
FILTER_VALIDATE_REGEXP | Custom pattern. |
Re-display values safely
PHP
<input name="email" value="<?= htmlspecialchars($email) ?>">
<?php if (isset($errors['email'])): ?>
<p class="err"><?= htmlspecialchars($errors['email']) ?></p>
<?php endif; ?>
Tip: Validation rules live next to the form. Don't scatter them across controllers — bundle into a "request" object so reading the rules is one stop.
Example
Example
<?php $errors = []; $name = trim($_POST['name'] ?? ''); $email = trim($_POST['email'] ?? ''); if ($name === '') $errors[] = 'Name required'; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Invalid email'; print_r($errors);Try it Yourself »
Exercise
Email validator filter constant.
filter_var($email, FILTER_VALIDATE
_);
Five letters.
Discussion
Loading…