2016/05/15 ThinkPHP3.2.2 表单自动验证实例 验证规则的数组 直接写在相应的控制器里

使用TP 3.2框架

验证规则也可以写到模型里,但感觉有些麻烦,

一是有时候不同页面验证的方式会不一样,

二是看到这个   Add  事件里的代码,就清楚要接收什么数据,如何验证数据能够在第一眼有个大致了解

①控制器代码页    

 1 <?php 
 2 namespace HomeController;
 3 use ThinkController;
 4 
 5 header("Content-type: text/html; charset=utf-8"); 
 6 
 7 class AddController extends Controller{
 8 
 9 public function Add()
10             {
11 
12         $rule=array(    //自动验证的规则数组
13          array('Ids','require','编号不能为空'),    
14          array('Name','require','用户名不能为空'),
15          array('Price','require','价格不能为空'),
16          array('Source','require','产地不能为空'),
17          );
18                 $m=D('fruit');
19                 if (empty($_POST)) {
20                     $this->display(); 
21                 }
22 
23                 else{
24                     
25                 $z=$m->field('Ids,Name,Price,Source')->validate($rule)->create();//create方法调用数组中的规则进行验证
26 
27                 // $m->Ids=$_POST['ids'];
28                 // $m->Name=$_POST['name'];
29                 // $m->Price=$_POST['price'];
30                 // $m->Source=$_POST['source'];
31                 //->field('Ids,Name,Price,Source')
32                 //var_dump($z);
33 
34                 if ($z) {
35                     $m->add();
36                     //$this->success('数据添加成功','User/User');
37                     $this->redirect('User/User');
38                 }
39                 else
40                 {
41                     //$this->error('数据添加失败');
42                     echo $m->getError();
43                 }
44                 
45             
46         }
47     
48         }
49 
50 
51 
52 
53 }

② 模板显示页面

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>添加</title>
 6 </head>
 7 <body>
 8 
 9 <div align="center" style="margin-top:30px; ">
10 <h1>添加页面</h1>
11     <form action="/tp/index.php/Home/Add/Add" method="post">
12         编号:<input type="text" name="Ids"><br><br>
13         名称:<input type="text" name="Name"><br><br>
14         价格:<input type="text" name="Price"><br><br>
15         产地:<input type="text" name="Source"><br><br>
16           <input type="submit" value="点击添加"></input>  <input type="reset" value="重置"></input>
17     </form>
18     
19 </div>
20 </body>
21 </html>

网络搜集到的相同方法的案例:

 1 public function anyvalidate(){
 2 
 3         //验证规则
 4 
 5         $rule=array(
 6 
 7             array('name','require','请输入姓名',1),//必须验证name
 8 
 9         );
10 
11  
12 
13         $m=M('user');
14 
15  
16 
17         //获取name,sex,contact数据到模型,并验证
18 
19         if(!$m->field('name,sex,contact')->validate($rule)->create())
20 
21             $this->error($m->getError());
22 
23  
24 
25         $result=$m->add();
26 
27  
28 
29         if(!$result)
30 
31             $this->error('添加失败');
32 
33  
34 
35         $this->success('添加成功',U('dir'));
36 
37     }
原文地址:https://www.cnblogs.com/haodayikeshu/p/5496655.html