According to the validation rules table on the previous page, the “Name,” “E-mail,” and “Gender” fields are mandatory in the HTML form and cannot be left empty.
Field |
Validation Rules |
Name |
Required: Must only contain letters and whitespace. |
|
Required: Must contain a valid email address (including @ and .). |
Website |
Optional: If provided, 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’ve introduced new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These variables will store error messages for the required fields. Additionally, we’ve added an if-else statement for each $_POST variable. This checks if the $_POST variable is empty using the PHP empty() function. If it’s empty, an error message is assigned to the respective error variable. If it’s not empty, the user input data is passed through the test_input() function.
// define variables and set to empty values if
|
Next, in the HTML form, we include a small script after each required field to display the appropriate error message if necessary (i.e., if the user attempts to submit the form without completing the required fields).
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
</form>
|
The next step involves validating the input data: ensuring the “Name” field contains only letters and whitespace, verifying if the “E-mail” field has a valid email address syntax, and if provided, confirming if the “Website” field contains a valid URL.