search
HomeBackend DevelopmentPHP ProblemPHP 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!

PHP form learning: How to verify the required fields in the form?

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:

PHP form learning: How to verify the required fields in the form?

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:

PHP form learning: How to verify the required fields in the form?

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:

PHP form learning: How to verify the required fields in the form?

PHP form learning: How to verify the required fields in the form?

PHP form learning: How to verify the required fields in the form?

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

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

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

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.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

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.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

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

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

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

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

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.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

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

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

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

Dreamweaver CS6

Visual web development tools