用户
 找回密码
 入住 CI 中国社区
搜索
查看: 3035|回复: 0
收起左侧

[版本 2.x] CI Post & Form Validation的3个使用技巧

[复制链接]
发表于 2012-8-14 21:43:01 | 显示全部楼层 |阅读模式

众所周知,CodeIgniter拥有大量的文档,但是有很多不错的代码没有出现在文档中,这里就有三个不错的小技巧,可以让你的开发变得更轻松。

返回所有POST项目并且进行XSS过滤,我们可以通过第二个boolean参数来设定,例如:

$fields = $this->input->post(NULL, TRUE);

允许你对所有的$_POST项进行操作,无须一条条的来。

使用Form Validation来测试任何变量。

这里有个“双重技巧”,如果你喜欢:第一,表单验证内部读和使用$ _POST数组,因此简单地写:

        $_POST['required_var' = '';
        $this->form_validation->set_rules('required_var', 'Required Var', 'required');
                if ($this->form_validation->run() == FALSE)
                {
                        echo validation_errors();
                }
        unset($_POST['required_var']);

虽然有点问题,完美的工作。还记得,表单验证库是……只是一个library。继续借其功能为您要去的地方,你可以在system/libraries目录中找到:

if (!$this->form_validation->valid_email('test'))
        {
                echo 'Not a valid email';
        }

你还可以处理表单数据传递给你的回调并返回它。如果你的回调返回以外的任何一个布尔值TRUE / FALSE假设数据是你的新处理表单数据。

换句话说,写一个回调如:

public function username_check($str)
        {
             return json_encode(array('data'=>'lots of additional data I looked up in my db'))
        }

will, instead of simply passing or failing a test, allow you to fully manipulate the data and pass it back to your controller function. (As a real-life example, on a recent project I needed to hit the database to check if a given airport code was valid before insert, but also wanted to insert some denormalized data about that airport at the same time. Since I was hitting the database anyway, I passed back the whole row of info I wanted & processed it for the insert.)

So...read those bits of fine print! There are some gems in there.

希望能够帮助到您.

(责任编辑:CIT信息网)

转载注明来源:http://www.cit.cn/tech/develop/codeIgniter/2012/0814/434.html

本版积分规则