且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CI设置表单验证规则

更新时间:2022-08-18 23:00:48

CodeIgniter 允许你为单个表单域创建多个验证规则,按顺序层叠在一起, 你也可以同时对表单域的数据进行预处理。要设置验证规则, 可以使用 set_rules() 方法:

$this->form_validation->set_rules();

上面的方法有 三个 参数:

  1. 第一个参数,表单域名 - 就是你给表单域取的那个名字。
  2. 第二个参数,表单域的 "人性化" 名字,它将被插入到错误信息中。例如, 如果你有一个表单域叫做 “user” ,你可能会给它一个人性化的名字叫做 “用户名” 。
  3. 第三个参数,为此表单域设置的验证规则。
  4. (可选的)当此表单域设置自定义的错误信息,如果没有设置该参数,将使用默认的。

注解

如果你想让表单域的名字保存在一个语言文件里,请参考 翻译表单域名称

下面是个例子,在你的控制器(Form.php)中紧接着验证初始化函数之后,添加这段代码:

$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');

你的控制器现在看起来像这样:

<?php

class Form extends CI_Controller {

    public function index()
    {
        $this->load->helper(array('form', 'url'));

        $this->load->library('form_validation');

        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required',
            array('required' => 'You must provide a %s.')
        );
        $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required');

        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('myform');
        }
        else
        {
            $this->load->view('formsuccess');
        }
    }
}

现在如果你不填写表单就提交,你将会看到错误信息。如果你填写了所有的表单域并提交,你会看到成功页。

注解

当出现错误时表单页将重新加载,所有的表单域将会被清空,并没有被重新填充。 稍后我们再去处理这个问题。

如何联系我:【万里虎】www.bravetiger.cn 【QQ】3396726884 (咨询问题100元起,帮助解决问题500元起) 【博客】http://www.cnblogs.com/kenshinobiy/