PHP Form Required
Required-field validation ensures important fields are not empty.
What is it?
Required-field validation ensures important fields are not empty.
Why do we use it?
It prevents incomplete submissions.
How does it work?
PHP trims the submitted value and checks whether it contains meaningful content.
Syntax
$value = trim($_POST['field'] ?? '');
if ($value === '') { }
Example
<?php
$name = trim($_POST['name'] ?? '');
if ($name === '') {
echo "Name is required";
} else {
echo "Name received";
}
?>
Example Explained
More Examples
<?php $phone = trim($_POST['phone'] ?? ''); if ($phone === '') echo "Phone is required"; ?>
⚠️ Important Rules
Check required fields on the server.
❌ Common Mistakes
Using isset alone and accepting empty strings.
🌍 Real-World Use
Admission, registration and contact forms.
📝 Practice Exercise
Make name, email, phone and course required.
💻 Try It Yourself
Write and run this PHP lesson inside the AIFA Coding Lab.