PHP form learning: How to verify the required fields in the form?
In the previous article, I brought you "PHP Form Learning: Form Input and Verification", which introduced the relevant knowledge of form input and verification in PHP in detail. In this article, we Let's continue to see how to validate the required fields in the form. I hope everyone has to help!
In the previous article, we learned about input in the form and simple validation of the form through PHP. When we enter information, we will not be prompted even if our information is not entered. In our daily life, when we need to fill in information, we must fill in some important information. If we do not fill it in, there will be a prompt message telling us where the information has not been filled in.
This is actually what we call a required field, so how is the effect that such a required field is required to be achieved? Then let's take a look at how to get the required fields and error messages in the form.
PHP required fields
We have encountered required fields when we fill in the information during daily registration. The required fields are where we fill in the information. time, it must be filled in, otherwise there will be no way to pass.
In the previous article, we have introduced the validation rules of the form. In the example we gave, we introduced: the validation rules of the name are necessary, and the validation rules of the E-mail are necessary. Among them, they must be A valid email address (containing '@
' and '.
'). A gender validation rule is required and one must be selected. This is a required field in our power.
In the example from the previous article, all input fields were optional because we did not validate them. So how can we achieve the effect that required fields are required?
At this time we can add some new variables to the following code: $nameErr
, $emailErr
, $genderErr
, and $websiteErr
.
These error variables will be displayed on required fields. We also added an if else
statement to 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.
Next let’s take a look at the actual application of these variables:
<?php // 定义变量并默认设为空值 $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "名字是必需的。"; } else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "邮箱是必需的。"; } 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 = "性别是必需的。"; } else { $gender = test_input($_POST["gender"]); } } ?>
The output results are currently not visible. This code needs to verify the form data through the form code.
The name verification rule is required, and the E-mail verification rule is required, which must be a valid email address (including '@' and '.'). A gender validation rule is required and one must be selected.
We are not able to display the error through the above code. If we submit the above code knowledge without writing anything in the three required fields input boxes of name, email and gender, it will be displayed on the page. error message. If it is not blank, it will be verified, and then the content in the lse statement will be executed. Then let's take a look at how to display the error information.
In the HTML example form, we added some scripts to each field. Each script will display an error message when the information is entered incorrectly. In order to achieve the purpose of outputting an error message if the user submits the form without filling in the information.
Let’s take a look at how to display error information through an example. An example is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PHP中文网</title> </head> <style> .error {color: #FF0000;} </style> <body> <?php // 定义变量并设置为空值 $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "姓名是必填的"; } else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "电邮是必填的"; } 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 = "性别是必选的"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2 id="PHP-nbsp-验证实例">PHP 验证实例</h2> <p><span class="error">* 必需的字段</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 姓名:<input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span> <br><br> 电邮:<input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span> <br><br> 网址:<input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span> <br><br> 评论:<textarea name="comment" rows="5" cols="40"></textarea> <br><br> 性别: <input type="radio" name="gender" value="female">女性 <input type="radio" name="gender" value="male">男性 <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="提交"> </form> <?php echo "<h2 id="您的输入">您的输入:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
After passing the verification data, if we click submit without filling in our marked name, email and gender information, the output will be as follows:
From the above example, we have completed the filling requirements of the required fields in the PHP form through the variables $nameErr, $emailErr, $genderErr, and $websiteErr, as well as the ifelse statement and error display.
If you feel that the text reminder is not eye-catching enough, it is more common in our daily life that when you click submit, there will be a small pop-up window on the page. Next, as a way to expand knowledge, let’s take a look at how Implement pop-up reminders.
The example is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PHP中文网</title> </head> <style> .error {color: #FF0000;} </style> <body> <?php // 定义变量并设置为空值 $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "<script language=\"javascript\"> //声明标识符 { alert(\"姓名是必填的\"); //弹出对话框 } </script>"; } else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "<script language=\"javascript\"> //声明标识符 { alert(\"电邮是必填的\"); //弹出对话框 } </script>"; } 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 = "<script language=\"javascript\"> //声明标识符 { alert(\"性别是必选的\"); //弹出对话框 } </script>"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2 id="PHP-nbsp-验证实例">PHP 验证实例</h2> <p><span class="error">* 必需的字段</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 姓名:<input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span> <br><br> 电邮:<input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span> <br><br> 网址:<input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span> <br><br> 评论:<textarea name="comment" rows="5" cols="40"></textarea> <br><br> 性别: <input type="radio" name="gender" value="female">女性 <input type="radio" name="gender" value="male">男性 <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="提交" onclick="MsgBox()"> </form> <?php echo "<h2 id="您的输入">您的输入:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
When we input the result normally, the output result is as follows:
When we do not output the result , the following pop-up window will appear on the page. If an item is not filled in, a pop-up window will remind you:
If you are interested, you can click on "PHP Video Tutorial" to learn more about PHP knowledge.
The above is the detailed content of PHP form learning: How to verify the required fields in the form?. For more information, please follow other related articles on the PHP Chinese website!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools