PHP Form Required Fields
In most forms, certain fields are mandatory (such as Name and Email). If a user leaves these fields empty, we should display an error message and prevent the data from being processed.
1. Error Variables Setup
The first step is to create error variables for each mandatory field. These are initialized as empty strings at the start of the script.
<?php
// Initialize variables with empty values
$nameErr = $emailErr = $genderErr = "";
$name = $email = $gender = "";
?>
2. Checking for Empty Fields
We use the empty() function to check if a field contains data. If it is empty, we assign a specific message to our error variable.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}
?>
3. Displaying Error Messages in HTML
Inside the form, we use PHP to echo the error messages. These are typically placed next to the input field, often styled in red.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
4. Keeping Data in the Form
If an error occurs, we want to ensure the user doesn't have to re-type everything. To do this, we echo the PHP variable inside the value attribute of the input field.
Name: <input type="text" name="name" value="<?php echo $name;?>">
Tip: Use CSS to define .error { color: #FF0000; } so that error messages stand out clearly to the user.