CodeIgniter 容许你为单个表单域建立多个验证规则,按顺序层叠在一块儿, 你也能够同时对表单域的数据进行预处理。要设置验证规则, 能够使用 set_rules() 方法:php
$this->form_validation->set_rules();
上面的方法有 三个 参数:html
注解ide
若是你想让表单域的名字保存在一个语言文件里,请参考 翻译表单域名称函数
下面是个例子,在你的控制器(Form.php)中紧接着验证初始化函数以后,添加这段代码:codeigniter
$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');
你的控制器如今看起来像这样:ui
<?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'); } } }
如今若是你不填写表单就提交,你将会看到错误信息。若是你填写了全部的表单域并提交,你会看到成功页。this
注解url
当出现错误时表单页将从新加载,全部的表单域将会被清空,并无被从新填充。 稍后咱们再去处理这个问题。spa