iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

FilterValidates
FILTER_VALIDATE_EMAILRFC-5321 email shape.
FILTER_VALIDATE_URLURL with scheme.
FILTER_VALIDATE_INTInteger string.
FILTER_VALIDATE_FLOATFloat string.
FILTER_VALIDATE_BOOL"true"/"false"/"on"/etc.
FILTER_VALIDATE_IPIPv4 / IPv6.
FILTER_VALIDATE_REGEXPCustom 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 _);

Test yourself

Q1. For email validation prefer…
Q2. Validation should run…
Q3. Re-displaying input safely uses…

Discussion

Loading…