PHP Forms - Required Fields
In this chapter, we will introduce how to set required fields in a form and handle error messages.
PHP - Required Fields
In the previous chapter, we introduced form validation rules. We can see that the "Name", "E-mail", and "Gender" fields are required and cannot be empty.
| Field | Validation Rules |
|---|---|
| Name | Required. + Must contain only letters and whitespace |
| Required. + Must contain a valid email address (with '@' and '.') | |
| Website | Optional. If present, it must contain a valid URL |
| Comment | Optional. Multi-line input field (textarea). |
| Gender | Required. Must select one. |
In the previous chapter, all input fields were optional.
In the following code, we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error variables will display error messages for the required fields. We have also added an if-else statement for each $_POST variable. These statements will check if the $_POST variable is empty (using PHP's empty() function). If it is empty, the corresponding error message will be displayed. If it is not empty, the data will be passed to the test_input() function:
<?php
// Define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER == "POST") {
if (empty($_POST)) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST);
}
if (empty($_POST)) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST);
}
if (empty($_POST)) {
$website = "";
} else {
$website = test_input($_POST);
}
if (empty($_POST)) {
$comment = "";
} else {
$comment = test_input($_POST);
}
if (empty($_POST)) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST);
}
}
?>
PHP - Display Error Messages
In the following HTML example form, we have added some scripts for each field. The scripts will display error messages if the information is entered incorrectly. (If the user submits the form without filling in the information, error messages will be output):
E-mail: *
Website:
Comment:
Gender: Female Male *
YouTip