In this tutorial, you will learn how to make HTML form fields required and make them retain their data after form submission. A simple and basic method in HTML5 is to add a required attribute to a form field as shown below:
<input type="text" name="name" required>
But, users can override this behavior by removing the required attribute from HTML by accessing the browser's developer tools, or it will not work if the browser does not support HTML5.
PHP Form Validation
A much better way to impose the required condition on HTML form fields is to use PHP.
Consider the following HTML form:
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<!-- Name Field -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
<!-- Email Field -->
<label for="email">E-mail:</label>
<input type="email" id="email" name="email" required>
<br>
<button type="submit">Submit</button>
</form>
In the following PHP code, we are using different variables, which are $nameReq
and $emailReq
, to store error messages for the required fields.
Additionally, we use if-else statements for each $_POST
variable to check if they are empty by utilizing PHP’s empty()
function. If a field is empty, the corresponding error message is stored in the respective error variable. If the field is not empty, the user input is processed through the test_input()
function for sanitization.
<?php
// Initialize variables to empty values
$nameReq = $emailReq = "";
$name = $email = "";
// Check if the form was submitted using POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate the 'name' field
if (empty($_POST["name"])) {
$nameReq = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
// Validate the 'email' field
if (empty($_POST["email"])) {
$emailReq = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}
?>
Display Error Messages and Retain Values
In the HTML form, we will add a small script after each required field to display the corresponding error message if the user attempts to submit the form without filling out the required fields. The error message will appear next to the field that was left empty.
Also, the PHP code inside the value attribute will ensure that the submitted value is retained inside the respective field.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<!-- Name Field -->
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error"><?php echo $nameReq;?></span>
<br><br>
<!-- Email Field -->
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error"><?php echo $emailReq;?></span>
<br><br>
<!-- Submit Button -->
<input type="submit" name="submit" value="Submit">
</form>