CodeIgniter中的Form_validation在进行Form的有效性验证时是一把利剑,非常有,而且它返回的出错信息也能非常方便的custom显示。Form_validation的源代码显示,validation置对POST请求起作用,这有两方面的意思。一个是对GET请求无效(废话:), 另一个是只要是POST请求,不管是请求来自Form提交,还是来自Service请求,它都能起作用。因此我就把它用到了我的Service中。
利用Form_validation的Service
function register()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required|is_unique[users.name]');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
if($this->form_validation->run() == true)
{
$model = new User_model;
$model->name = $this->input->post('name');
$model->email = $this->input->post('email');
$model->password = SHA1($this->input->post('password'));
$model->register_time = date('Y-m-d H:i:s');
$this->db->insert('users', $model);
}
else
{
$this->output->set_status_header('400');
$this->output->set_output(json_encode($this->form_validation->error_array()));
}
}
Form_validation能很好的工作,但是问题是在validation失败时,返回的错误信息是包含了Html Tag的,比如默认的P元素。
在Form_validation的源代码中,无论是
public function error($field = '', $prefix = '', $suffix = '')
public function error_string($prefix = '', $suffix = '')
,返回的错误信息都包含的Html元素内。当然你可以把自定义元素为一个“空格”(不能为0个空格),但是这样的做法显然太为了解决问题而解决了。
扩展Form_validation
Form_validation的源码中有一个字段叫做$_error_array,用来存储所有的validation失败的信息。可惜这个字段是protected的,直接是无法访问的。不过protected的字段,继承一下不就能用了吗?那就来扩展一下吧。
class My_Form_validation extends CI_Form_validation{
function __construct(){
parent::__construct();
}
function error_array(){
if(count($this->_error_array)===0){
return null;
}else{
return $this->_error_array;
}
}
}
新建一个error_array函数,把本来protected的字段给暴露出来,然后就可以象第一段Service代码中那样来调用了。
$this->form_validation->error_array();