Required Fields Validation in PHP - GeeksforGeeks

Required Fields Validation in PHP

Last Updated : 28 Oct, 2026

Required fields validation in PHP ensures that users provide values for mandatory form fields before the data is processed. PHP uses functions such as empty() and trim() to check whether submitted fields contain valid, non-empty values.

Checks Whether Required Fields Are Empty

PHP can validate required form fields by checking the submitted values before processing them.

  • The empty() function checks whether a variable is empty or evaluates to false, including when its value is 0 or "0".
  • The trim() function removes whitespace from the beginning and end of a string, helping identify inputs that contain only spaces.
  • The isset() function checks whether a variable is declared and is not null.
  • Server-side validation is necessary because HTML required attributes can be bypassed.

Validates Required Form Fields

The following example checks whether the name and email fields contain values before processing the submitted form.

PHP
//Driver Code Starts
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Required Fields Validation in PHP</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 40px 20px;
        }

        .form-container {
            max-width: 400px;
            margin: auto;
            padding: 25px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        h2 {
            text-align: center;
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
        }

        input {
            width: 100%;
            padding: 10px;
            margin-bottom: 18px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }

        button {
            width: 100%;
            padding: 12px;
            background-color: #3f74ac;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #b9d5f3;
        }

        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 4px;
        }

        .error {
            background-color: #ffe6e6;
            color: #b30000;
        }

        .success {
            background-color: #e6ffed;
            color: #036d28;
        }
    </style>
</head>
//Driver Code Ends

<body>

<div class="form-container">
    <h2>Registration Form</h2>

    <?php
    $message = '';
    $messageClass = '';

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');

        if ($name === '' || $email === '') {
            $message = 'Name and email are required.';
            $messageClass = 'error';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $message = 'Please enter a valid email address.';
            $messageClass = 'error';
        } else {
            $message = 'Form submitted successfully!';
            $messageClass = 'success';
        }
    }

    if ($message !== '') {
        echo '<p class="message ' . $messageClass . '">'
            . htmlspecialchars($message, ENT_QUOTES, 'UTF-8')
            . '</p>';
    }
    ?>

    <form method="post" action="">
        <label for="name">Full Name:</label>
        <input
            type="text"
            id="name"
            name="name"
            value="<?= htmlspecialchars($_POST['name'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
            required
        >

        <label for="email">Email:</label>
        <input
            type="email"
            id="email"
            name="email"
            value="<?= htmlspecialchars($_POST['email'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
            required
        >

        <button type="submit">Submit</button>
    </form>
</div>

</body>

//Driver Code Starts
</html>
//Driver Code Ends

Output:

Validates Multiple Required Fields

PHP can validate multiple required fields using an array and a loop, avoiding repetitive checks.

PHP
//Driver Code Starts
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Required Fields Validation in PHP</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 40px 20px;
        }

        .form-container {
            max-width: 400px;
            margin: auto;
            padding: 25px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        h2 {
            text-align: center;
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
        }

        input,
        textarea {
            width: 100%;
            padding: 10px;
            margin-bottom: 18px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
            font: inherit;
        }

        textarea {
            resize: vertical;
        }

        button {
            width: 100%;
            padding: 12px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }

        .message {
            padding: 12px;
            margin-bottom: 18px;
            border-radius: 4px;
        }

        .error {
            background-color: #ffe6e6;
            color: #b30000;
        }

        .success {
            background-color: #e6ffed;
            color: #176b35;
        }
    </style>
</head>
//Driver Code Ends

<body>

<div class="form-container">
    <h2>Contact Form</h2>

    <?php
    $errors = [];
    $success = false;

    $name = '';
    $email = '';
    $message = '';

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $message = trim($_POST['message'] ?? '');

        $requiredFields = [
            'Name' => $name,
            'Email' => $email,
            'Message' => $message
        ];

        foreach ($requiredFields as $field => $value) {
            if ($value === '') {
                $errors[] = "$field is required.";
            }
        }

        if (empty($errors)) {
            $success = true;
        }
    }

    if (!empty($errors)) {
        echo '<div class="message error">';

        foreach ($errors as $error) {
            echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8') . '<br>';
        }

        echo '</div>';
    }

    if ($success) {
        echo '<div class="message success">';
        echo 'All required fields are filled.';
        echo '</div>';
    }
    ?>

    <form method="post" action="">
        <label for="name">Name:</label>
        <input
            type="text"
            id="name"
            name="name"
            value="<?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>"
            required
        >

        <label for="email">Email:</label>
        <input
            type="email"
            id="email"
            name="email"
            value="<?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?>"
            required
        >

        <label for="message">Message:</label>
        <textarea
            id="message"
            name="message"
            rows="4"
            required
        ><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></textarea>

        <button type="submit">Submit</button>
    </form>
</div>

</body>

//Driver Code Starts
</html>
//Driver Code Ends


  • The $requiredFields array stores the names of mandatory fields.
  • The foreach loop checks each field for an empty or whitespace-only value.
  • The $errors array stores validation messages for missing fields.
  • The form can be processed only after all required fields pass validation.

Output:

Note: Required field validation checks whether a value has been provided. Additional validation, such as filter_var() for email addresses, is needed to verify that the value follows the expected format.

Comment