PHP - Required fields
In the previous chapter we have introduced the validation rules of the table, we can see that the "Name", "E-mail", and "Gender" fields are required. Each field cannot be empty.
Field + Can only contain letters and spaces
E-mail Required. + Must contain a valid email address (including "@" and ".")
URL If present, it must contain a valid URLRemarks Optional. Multiline fields (text fields).
Gender Required. Required to select one.
If in the previous chapter, all input fields are optional.
In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr.. These error variables will be displayed on required fields. We 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 not empty, the data will be passed to the test_input() function:
PHP - Display error message
In the following HTML example form, we have added some scripts for each field , each script will display an error message when incorrect information is entered. (If the user submits the form without filling in the information, an error message will be output):
View code »