PHP CHAPTER 26

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

PHP Syntax
$value = trim($_POST['field'] ?? '');
if ($value === '') { }
💻

Example

PHP Example
<?php

$name = trim($_POST['name'] ?? '');

if ($name === '') {
    echo "Name is required";
} else {
    echo "Name received";
}

?>
🔍

Example Explained

trim removes extra spaces. The comparison checks whether the final value is empty.
🚀

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.

Open Coding Lab →