Input Validation Techniques
Check required fields, types, and lengths before processing.
Input Validation Techniques is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Validate Input?
Never trust data from users. Validation ensures data meets your requirements before you process it. It prevents:
- Database errors from wrong types
- Business logic bugs from unexpected values
- Security vulnerabilities from malicious input
Required Field Check
Check that required fields are not empty after trimming whitespace:
<?php
$errors = [];
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
if (empty($name)) {
$errors['name'] = 'Name is required';
}
if (empty($email)) {
$errors['email'] = 'Email is required';
}
if (!empty($errors)) {
// show errors
}Type Validation
Validate that values are the expected type before using them:
<?php
$age = $_POST['age'] ?? '';
// Method 1: filter_var
$validAge = filter_var($age, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 120]
]);
if ($validAge === false) {
$errors[] = 'Age must be a number between 1 and 120';
}Email Validation
Validate email addresses with the FILTER_VALIDATE_EMAIL filter:
<?php
$email = trim($_POST['email'] ?? '');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email address';
}
// Also check domain has MX record for extra validation
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
[$user, $domain] = explode('@', $email);
if (!checkdnsrr($domain, 'MX')) {
$errors[] = 'Email domain not found';
}
}String Length Validation
Enforce minimum and maximum string lengths:
<?php
$username = trim($_POST['username'] ?? '');
$len = mb_strlen($username);
if ($len < 3) {
$errors[] = 'Username must be at least 3 characters';
}
if ($len > 30) {
$errors[] = 'Username must be at most 30 characters';
}Whitelist Validation
Validate against an allowed set of values (whitelist) rather than trying to block bad values:
<?php
$allowedRoles = ['admin', 'editor', 'viewer'];
$allowedSorts = ['name', 'date', 'price'];
$role = $_POST['role'] ?? '';
$sort = $_GET['sort'] ?? 'name';
if (!in_array($role, $allowedRoles, true)) {
$errors[] = 'Invalid role selected';
}
// Default to 'name' if sort value invalid
if (!in_array($sort, $allowedSorts, true)) {
$sort = 'name';
}URL and IP Validation
Validate URLs and IP addresses with built-in filters:
<?php
$url = $_POST['website'] ?? '';
$ip = $_POST['ip'] ?? '';
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$errors[] = 'Invalid URL';
}
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$errors[] = 'Invalid IPv4 address';
}Pattern Validation with Regex
Use preg_match() for custom format validation:
<?php
$phone = preg_replace('/[^0-9+]/', '', $_POST['phone'] ?? '');
// Validate format: +1234567890
if (!preg_match('/^\+?[0-9]{7,15}$/', $phone)) {
$errors[] = 'Invalid phone number';
}
// Validate date format YYYY-MM-DD
$date = $_POST['date'] ?? '';
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
$errors[] = 'Date must be in YYYY-MM-DD format';
}Date Validation
Validate that a string represents a real calendar date:
<?php
function isValidDate(string $date, string $format = 'Y-m-d'): bool {
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
}
var_dump(isValidDate('2024-02-29')); // true (2024 is leap year)
var_dump(isValidDate('2023-02-29')); // false (not a leap year)
var_dump(isValidDate('2024-13-01')); // false (no month 13)File Upload Validation
Validate uploaded files by type, size, and error code:
<?php
$file = $_FILES['photo'] ?? null;
if ($file) {
if ($file['error'] !== UPLOAD_ERR_OK) {
$errors[] = 'Upload failed with error: ' . $file['error'];
} elseif ($file['size'] > 2 * 1024 * 1024) {
$errors[] = 'File exceeds 2MB limit';
} elseif (!in_array(mime_content_type($file['tmp_name']), ['image/jpeg', 'image/png'])) {
$errors[] = 'Only JPEG and PNG files allowed';
}
}Displaying Validation Errors
Show errors inline next to form fields and preserve user-entered values:
<?php
// Preserve entered values:
$name = htmlspecialchars($_POST['name'] ?? '');
?>
<form method="POST">
<input name="name" value="<?= $name ?>">
<?php if (isset($errors['name'])): ?>
<p class="error"><?= htmlspecialchars($errors['name']) ?></p>
<?php endif; ?>
<button type="submit">Submit</button>
</form>Quick Check
What is a whitelist approach to validation?
Recap: Input Validation
Validation best practices:
- Check required fields after trim()
- Use
filter_var()for type and format validation - Whitelist allowed values with
in_array() - Use
preg_match()for custom patterns - Validate file uploads: error code, size, MIME type
- Preserve user input when re-displaying forms with errors
Frequently asked questions
Is the “Input Validation Techniques” lesson free?
Yes — the full text of “Input Validation Techniques” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Input Validation Techniques”?
Check required fields, types, and lengths before processing. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Input Validation Techniques” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- GET vs POST: When to Use Each
- Reading Form Data with Superglobals
- Input Validation Techniques
- Sanitizing User Input