


Detailed explanation of ThinkPhp framework form verification and ajax verification examples
There are two ways to verify tp data, one is static and the other is dynamic. The previous form verification was written in js. The verification of 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 methods of data validation:
Static method: Define validation rules through the $_validate attribute in the model class. 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. Write the corresponding html file in thinkphp\Application\Home\View\Test
nbsp;html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <meta> <title>无标题文档</title> <style> *{ font-family:微软雅黑; padding:0px; margin:0px auto} </style>
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 method in thinkphp\Application\Home\View\Test html file
nbsp;html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <meta> <title>无标题文档</title> <style> </style><script> </script>
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
tp dynamic verification and static verification both have a big shortcoming, that is, when an error message is prompted, they have to jump to other pages to display the error. information. 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
nbsp;html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <meta> <script></script> <title>无标题文档</title> <style> </style> <p>用户名:<input></p> <p><input></p> <script> $("#btn").click(function(){ var uid = $("#uid").val(); $.ajax({ url:"__CONTROLLER__/test", data:{uid:uid}, type:"POST", dataType:"TEXT", success: function(data){ alert(data); } }) }) </script>
Related recommendations:
PHP users Verify PHP+Ajax verification code to verify user login
Ajax verification username example code
ajax verification username and password, ajax verification username_ PHP tutorial
The above is the detailed content of Detailed explanation of ThinkPhp framework form verification and ajax verification examples. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

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.