Home  >  Article  >  Backend Development  >  ThinkPHP表单自动验证实例_PHP

ThinkPHP表单自动验证实例_PHP

WBOY
WBOYOriginal
2016-05-31 19:29:34963browse

ThinkPHP

本文实例讲述了ThinkPHP表单自动验证的实现方法。分享给大家供大家参考。具体方法如下:

该示例代码采用TP 3.2框架实现。具体代码如下:

代码如下:

public function add_post(){
        //验证规则
        $rule=array(
            array('name','require','请输入姓名',1),//必须验证name
        );
 
        $m=M('user');
 
        //获取name,sex,contact数据到模型,并验证
        if(!$m->field('name,sex,contact')->validate($rule)->create())
            $this->error($m->getError());
 
        $result=$m->add();
 
        if(!$result)
            $this->error('添加失败');
 
        $this->success('添加成功',U('dir'));
}

其中的验证规则也可以写到模型里,但笔者感觉有些麻烦,一是有时候不同页面验证的方式会不一样,二是看到这个add_post事件里的代码,就清楚要接收什么数据,如何验证数据能够在第一眼有个大致了解,所以总结出了此方式。

希望本文所述对大家的ThinkPHP程序开发有所帮助。

Statement:
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