PHP Form - Required Fields
In this section we'll show you how to set up the form required fields and error messages.
PHP - Required field
In the previous section we covered the validation rules for the table, and we can see that the "Name", "E-mail", and "Gender" fields are required and each field cannot be empty.
Field | Verification rule |
---|---|
Name | Required.+ Only only letters and spaces |
Required.+ Requirements contain a valid email address (including "@" and ".") | |
Website | Optional.If there is, it must contain a valid URL |
Comment | Optional.Multi-line fields (text domain). |
Gender | Required.Must Select One |
If in the previous section, all input fields are optional.
We've added some new variables to the following code: $nameErr, $emailErr, $genderErr, and $websiteErr. T hese error variables appear on the required fields. W e also added _POST if else statement for each $variable. T hese statements check whether the $_POST variable is empty (empty() function using php). I f empty, the corresponding error message is displayed. If it is not empty, the data is passed to test_input() function:
<?php
// 定义变量并默认设为空值
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["website"]))
{$website = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}
}
?>
PHP - Displays an error message
In the HTML instance form below, we've added some scripts to each field that display error messages when the information is entered incorrectly. (If the user submits the form without filling out the information, the error message is output):
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;? ></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;? ></span>
<br><br>
<label>Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;? ></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Run an instance . . .