Table of Contents
PHP 验证实例
您的输入:
Home Backend Development PHP Problem PHP form learning: How to verify the required fields in the form?

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

Oct 29, 2021 am 11:51 AM
php form validation

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"]);
     }
 }
 ?>
Copy after login

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>
Copy after login

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>
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles