


Detailed explanation of form validation and ajax validation in ThinkPhp framework
There are two ways to verify tp data, one is static and the other is dynamic. Below, the editor will bring you ThinkPhp framework form verification and ajax verification issues. Friends who are interested should take a look.
Previous form verification was written in js, and the verification of the tp framework can also be used here. But comparing the two, js verification is better, because tp framework verification will run background code, so the running speed and efficiency will decrease.
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. The verification code must be written in the model layer, that is, the Model.
There are two ways to verify data:
Static method: Define verification through the $_validate attribute in the model class rule. After the static method is defined, it can be used elsewhere.
Dynamic method: Use the validate method of the model class to dynamically create automatic validation rules. The dynamic method is more flexible. It can be written wherever it is used and cannot be used elsewhere.
No matter what method is used, the definition of verification rules is a unified rule, and the definition format is:
<?php namespace Home\Controller; use Think\Controller; class TestController extends Controller { public function add() { if(empty($_POST)) { $this->show(); } else { $y=new \Home\Model\YongHuuModel(); $r=$y->create(); if($r) { $y->add(); } else{ die($y->getError()); } } } }
2. In thinkphp\Application\Home\View \Test writes the corresponding html file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <style type="text/css"> *{ font-family:微软雅黑; padding:0px; margin:0px auto} </style> <body> <form action="__ACTION__" method="post"> <p>用户名:<input type="text" name="uid" /></p> <p>密码:<input type="text" name="pwd" /></p> <p>确认密码:<input type="text" name="pwd1" /></p> <p>姓名:<input type="text" name="name" /></p> <p>邮箱:<input type="text" name="email" /></p> <p>年龄:<input type="text" name="age" /></p> <p><input type="submit" value="提交" /></p> </form> </p> </body> </html>
3. Write the model file in thinkphp\Application\Home\Model, which is the verification method.
<?php namespace Home\Model; use Think\Model; class YongHuuModel extends Model { protected $tablePrefix = ""; protected $trueTableName = 'yonghuu'; //真实表名 //protected $patchValidate = true; protected $_validate = array( array('uid','require','用户名不能为空!'), array('pwd','pwd1','两次输入的密码不一致!',0,'confirm'), //两个字段是否相同 array('email','email','邮箱格式不正确'), array('name','/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/','身份证号不正确!',0,'regex'), array('age','18,50','年龄不在范围内',0,'between'), ); }
2. Dynamic verification
1. Write the method in Application\Home\Controller
<?php namespace Home\Controller; use Think\Controller; class TestController extends Controller { public function add() { if(empty($_POST))//如果post数组为空 { $this->show();//显示add.html页面 } else//如果post数组不为空 { $y = D("YongHu"); $arr = array(//动态验证就是需要在哪验证就在哪里写验证方法。 array("uid","require","用户名不能为空",0),//讲验证的方法写在方法里面 ); if($y->validate($arr)->create())//这里要先调用validate方法,然后将写的验证方法放到validate里面 { $y->add(); } else { die($y->getError()); } } } }
2. Write the corresponding html file in thinkphp\Application\Home\View\Test
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> </style> </head> <body> <form action="__ACTION__" method="post"> <p>用户名:<input type="text" name="uid" /></p> <p>密码:<input type="text" name="pwd" /></p> <p>确认密码:<input type="text" name="pwd1" /></p> <p>姓名:<input type="text" name="name" /></p> <p>邮箱:<input type="text" name="email" /></p> <p>年龄:<input type="text" name="age" /></p> <p><input type="submit" value="提交" /></p> </form> </body> <script type="text/javascript"> </script> </html>
3 .Write the model file in thinkphp\Application\Home\Model.
<?php namespace Home\Model; use Think\Model; class YongHuModel extends Model { protected $tablePrefix = "";//表示表格前缀为空,就是没有前缀。 protected $trueTableName = "yonghu";//如果不写这句话,会自动去找Yong_Hu这张表,这是默认的表格的命名。这里要写上实际的表格的名字。 }
3. Ajax verification
There is a big difference between tp dynamic verification and static verification The disadvantage is that when an error message is prompted, it must jump to other pages to display the error message. If you need to display an error message on the current page, you need to use ajax for verification.
1. Write display and ajax processing methods
<?php namespace Home\Controller; use Think\Controller; class TestController extends Controller { public function tianjia()//添加方法,用来显示页面 { $this->show(); } public function test()//ajax处理方法 { $y = D("YongHu"); $arr = array(//动态验证就是需要在哪验证就在哪里写验证方法。 array("uid","require","用户名不能为空"),//讲验证的方法写在方法里面 ); if($y->validate($arr)->create())//这里要先调用validate方法,然后将写的验证方法放到validate里面 { $this->ajaxReturn("通过验证","eval"); } else { $this->ajaxReturn($y->getError(),"eval"); } } }
2. Write display page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="__PUBLIC__/js/jquery-1.11.2.min.js"></script> <title>无标题文档</title> <style type="text/css"> </style> </head> <body> <p>用户名:<input id="uid" type="text" name="uid" /></p> <p><input id="btn" type="button" value="验证" /></p> </body> <script type="text/javascript"> $("#btn").click(function(){ var uid = $("#uid").val(); $.ajax({ url:"__CONTROLLER__/test", data:{uid:uid}, type:"POST", dataType:"TEXT", success: function(data){ alert(data); } }) }) </script> </html>
The above is the detailed content of Detailed explanation of form validation and ajax validation in ThinkPhp framework. For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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,

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

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

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 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.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.
