Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP Forms - Required Fields

PHP Forms - Required Fields


This section will introduce how to set form required fields and error messages.


PHP - Required Fields

In the previous section we introduced the form validation rules. We can see that the "Name", "E-mail", and "Gender" fields are required and must not be empty.

Field Validation Rules
Name Required. + can only contain letters and whitespace
E-mail Required. + must contain a valid email address (including "@" and ".")
Website Optional. If present, it must contain a valid URL
Notes Optional. Multi-line field (text area).
Gender Required. Must select one.

If, in the previous sections, all input fields were optional.

In the code below we added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error variables will be displayed on the required fields. We also added an if-else statement for each $_POST variable. These statements check whether the $_POST variable is empty (using PHP's empty() function). If empty, the corresponding error message is displayed. If not empty, the data is passed to the test_input() function:






PHP - Displaying Error Messages

In the HTML example form below, we added some scripts for each field; each script will display an error message when the information is entered incorrectly. (If the user submits the form without filling in information, an error message will be output):



名字: *

E-mail: *

网址:

备注:

性别: 女 男 *

View Code »