Home > PHP Framework > ThinkPHP > body text

Introduction to ThinkPHP framework form validation

Release: 2020-05-12 09:30:04
forward
3033 people have browsed it

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,验证规则,错误提示,[验证条件,附加规则,验证时间]),
......
);
Copy after login

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;),
    
    );    
    
}
Copy after login

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();    
            }
Copy after login

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

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();    
            }
            
        }    
    }
Copy after login

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 src="../../../../../jquery-1.11.2.min.js"></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);
                }
            });        
        })
Copy after login

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;);
            }
    }
Copy after login
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!

Related labels:
source:cnblogs.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template