From the validation rules in the previous section, we see that the "Name", "E-mail" and "Gender" fields are required. These fields cannot be empty and must be filled in the HTML form.
Field Validation Rule
Name Required. Must contain letters and spaces.
E-mail required. Must contain a valid email address (including @ and .).
Website Optional. If optional, a valid URL must be included.
Comment Optional. Multi-line input field (text box).
Gender required. One must be selected.
In the previous section, all input fields were optional.
In the code below we have added some new variables: $nameErr, $emailErr, $genderErr and $websiteErr. These error variables hold the error message for the requested field. We also added an if else statement to each $_POST variable. This statement checks whether the $_POST variable is empty (via the PHP empty() function). If empty, the error message is stored in a different error variable. If not empty, the user input data is sent through the test_input() function:
PHP - Show error message
In the HTML form, we added a little script after each requested field. Appropriate error messages are generated if required (if the user attempts to submit the form without filling in required fields):
Example
您的输入:"; echo $name; echo "PHP 验证实例
* 必需的字段
PHP Validation Example
* Required fields
Name: *
Email: *
Website:
Comments:
Gender: Female Male
Your input: