CI设置表单验证规则

CodeIgniter 容许你为单个表单域建立多个验证规则,按顺序层叠在一块儿, 你也能够同时对表单域的数据进行预处理。要设置验证规则, 能够使用 set_rules() 方法:php

$this->form_validation->set_rules(); 

上面的方法有 三个 参数:html

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

注解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

相关文章
相关标签/搜索