search
HomePHP FrameworkThinkPHPIntroduction to ThinkPHP framework form validation

Introduction to ThinkPHP framework form validation

Verify the form registered to the test table

Verify the form before registration:

Verify that the user name is not empty, twice The entered password must be consistent (equality verification), the age must be between 18 and 50 (range verification), and the email format must be regular verification.

Automatic verification is a data verification method provided by the ThinkPHP model layer, which can automatically perform data verification when using create to create a data object.

Data verification can perform verification operations on data types, business rules, security judgments, etc.

There are two methods of data validation:

  • Static method: Define validation rules through the $_validate attribute in the model class.

  • Dynamic method: Use the validate method of the model class to dynamically create automatic validation rules.

No matter what method is used, the definition of verification rules is a unified rule, and the definition format is:

array(
array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]),
array(验证字段2,验证规则,错误提示,[验证条件,附加规则,验证时间]),
......
);

Validation field (required)

The name of the form field that needs to be verified. This field is not necessarily a database field, but can also be some auxiliary fields of the form, such as confirming passwords and verification codes, etc. When there are individual validation rules that have nothing to do with fields, the validation fields can be set at will. For example, expire validity rules have nothing to do with form fields. If field mapping is defined, the validation field name here should be the actual data table field rather than the form field.

Verification rules (required)

The rules for verification need to be combined with additional rules. If additional rules for regular verification are used, the system also has some built-in rules. Commonly used regular verification rules can be used directly as verification rules, including: require field, email address, url address, currency, and number.

Prompt information (required)

Used to define prompt information after verification failure

Verification conditions (optional)

Includes the following situations:

  • self::EXISTS_VALIDATE or 0, verify if the field exists (default)

  • self ::MUST_VALIDATE or 1 Must verify

  • self::VALUE_VALIDATE or 2 Verify when the value is not empty

Additional rules ( Optional)

Use with verification rules, including the following rules:

Introduction to ThinkPHP framework form validation

Verification time (optional)

  • self::MODEL_INSERT or 1 verify when adding data

  • ##self::MODEL_UPDATE or 2 verify when editing data

  • self::MODEL_BOTH or 3 Verify in all cases (default)

You need to pay attention to the verification time here. It is not the only three cases. You can according to business needs Add additional verification time.

There are two methods of verification: static verification and dynamic verification.

1. Static verification

Predefine the automatic verification rules of the model in the model class, which we call static definition.

When verifying, add verification conditions to the Model of the test table: Create a new testModel.class.php, and define the $_validate attribute in the model class as follows:

<?php
namespace Home\Model;
use Think\Model;
class testModel extends Model
{
    //静态验证
    protected $_validate = array(    
        array(&#39;uid&#39;,&#39;require&#39;,&#39;用户名不能为空&#39;),        
        array(&#39;pwd&#39;,&#39;require&#39;,&#39;密码不能为空&#39;),
        array(&#39;repwd&#39;,&#39;pwd&#39;,&#39;确认密码不正确&#39;,1,&#39;confirm&#39;),
        array(&#39;age&#39;,&#39;18,50&#39;,&#39;年龄必须在18-50岁之间&#39;,1,&#39;between&#39;),
        array(&#39;email&#39;,&#39;email&#39;,&#39;邮箱格式不正确&#39;),
    
    );    
    
}

After defining the verification rules, It can be automatically called when using the create method to create a data object:

<?php
namespace Home\Controller;
use Home\Controller\CheckController;
class ZhuCeController extends CheckController
{
    function ZhuCe()
    {
        //静态验证,不能在后面直接显示,必须全部通过验证才能注册
        $cw = "";
        if(!empty($_GET))
        {
            $cw = $_GET["cw"];    
        }
        if(empty($_POST))
        {
            $this->assign("error",$cw);
            $this->display();
        }
        else
        {
            $model = new \Home\Model\testModel();
            //$model = D("test");    //动态验证可以用D方法
             
            if(!$model->create())
            {                
                $e = $model->getError();
                $url = "ZhuCe/cw/{$e}";
                $this->error("注册失败!",$url,1);
            }
            else
            {
                $model->add();    
            }

Template ZhuCe.html:

<body>
<form action="__ACTION__" method="post">
<div>用户名:<input type="text" name="uid" id="uid" /> </div><br />
<div>密码:<input type="text" name="pwd" id="pwd" /></div><br />
<div>确认密码:<input type="text" name="repwd" id="repwd" /> </div><br />
<div>年龄:<input type="text" name="age" id="age" /> </div><br />
<div>邮箱:<input type="text" name="email" id="email" /> </div><br />
<div>姓名:<input type="text" name="name" /></div><br />
<div><{$error}></div>   <!--显示错误信息-->
<input type="submit" value="注册" />
</form>

Request the ZhuCe method:

Introduction to ThinkPHP framework form validation

2. Dynamic verification

If you adopt dynamic verification, it is more flexible. You can use different verification rules when operating the same model according to different needs, such as the above The static verification method can be changed to:

<?php
namespace Home\Controller;
use Home\Controller\CheckController;
class ZhuCeController extends CheckController
{
    function ZhuCe()
    {        
        if(empty($_POST))
        {            
            $this->display();
        }
        else
        {
            //$model = new \Home\Model\testModel();
            $model = D("test");    //动态验证可以用D方法            
            //动态验证
            $rules = array(
                array(&#39;uid&#39;,&#39;require&#39;,&#39;用户名不能为空&#39;)
            );
            //调用validate()加入验证规则
            $r = $model->validate($rules)->create();//若验证失败返回false,成功返回注册的test表数组信息
            //var_dump($r);
            if(!$r)
            {
                echo $model->getError(); //若验证失败则输出错误信息    
            }
            else
            {
                $model->add();    
            }
            
        }    
    }

We can also display the error message directly behind the form, which requires the use of ajax. Take verifying that the user name is not empty as an example:

In the template ZhuCe.html:

<script ></script>  
</head>

<body>
<form action="__ACTION__" method="post">
<div>用户名: <input type="text" name="uid" id="uid" /> <span id="ts"></span></div><br />
<div>密码:  <input type="text" name="pwd" id="pwd" /> <span id="pts"></span></div><br />
<div>确认密码:<input type="text" name="repwd" id="repwd" /> <span id="rpts"></span></div><br />
<div>年龄:  <input type="text" name="age" id="age" /> <span id="nts"></span></div><br />
<div>邮箱:  <input type="text" name="email" id="email" /> <span id="ets"></span></div><br />
<div>姓名:  <input type="text" name="name" /></div><br />
<!--<div><{$error}></div> -->  <!--显示错误信息-->
<input type="submit" value="注册" />
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(e) {
    $("#uid").blur(function(){
        var uid = $(this).val();
        $.ajax({
            
            url:"__CONTROLLER__/Yhm",  <!--提交到方法,而不是页面-->
            data:{uid:uid},   <!--因为做的是表单验证,所以提交时要与表单name值一致,相当于提交表单 -->
            type:"POST",
            dataType:"TEXT",   <!--返回数据类型要与ajaxReturn中的参数对应,TEXT对应eval-->
            success: function(data){
                //alert(data);
                var str = "";
                if(data.trim()=="OK")
                {
                    str = "<span style=&#39;color:green&#39;>"+data+"</span>";
                }
                else
                {
                    str = "<span style=&#39;color:red&#39;>"+data+"</span>";    
                }
                
                $("#ts").html(str);
                }
            });        
        })

Create another Yhm method in the ZhuCe controller:

//验证用户名非空
    function Yhm()
    {
        $model = D("test");    
        $rules = array(
                array(&#39;uid&#39;,&#39;require&#39;,&#39;用户名不能为空&#39;)
            );
            
            if(!$model->validate($rules)->create())
            {
                $fh = $model->getError();
                $this->ajaxReturn($fh,&#39;eval&#39;);  //ajax返回数据,默认返回json格式,eval返回字符串,因为dataType是TEXT,所以用eval格式
            }
            else
            {
                $fh = "OK";    
                $this->ajaxReturn($fh,&#39;eval&#39;);
            }
    }

Request the ZhuCe method :

Introduction to ThinkPHP framework form validation

Other verification methods are similar. Submit the corresponding data to the corresponding method and use the corresponding verification rules.

Recommended tutorial: "

TP5"

The above is the detailed content of Introduction to ThinkPHP framework form validation. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

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尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)