PHP Form Validation
Form validation checks whether submitted data follows application rules.
What is it?
Form validation checks whether submitted data follows application rules.
Why do we use it?
Validation prevents incomplete or invalid data from entering your application.
How does it work?
PHP receives the input, checks each rule, collects errors and processes the data only when valid.
Syntax
if (!condition) {
$errors[] = "Error message";
}
Example
<?php
$email = $_POST['email'] ?? '';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email";
} else {
echo "Valid email";
}
?>
Example Explained
More Examples
<?php $name = trim($_POST['name'] ?? ''); if ($name === '') echo "Name is required"; ?>
⚠️ Important Rules
Server-side validation is necessary even when HTML validation exists.
❌ Common Mistakes
Trusting only browser-side validation.
🌍 Real-World Use
Registration, admission, login and checkout forms.
📝 Practice Exercise
Validate name, email and phone fields.
💻 Try It Yourself
Write and run this PHP lesson inside the AIFA Coding Lab.