Input Validation Techniques
Check required fields, types, and lengths before processing.
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
}All lessons in this course
- GET vs POST: When to Use Each
- Reading Form Data with Superglobals
- Input Validation Techniques
- Sanitizing User Input