在CodeIgniter中设置表单验证规则

时间:2013-03-24 12:12:13

标签: codeigniter validation

我有这些问题,我想在“文本”类型的三种输入形式上设置规则,我的规则是至少这三种中的一种具有值(三,),我不知道如何在CI中设置它们,因为它们在run()被触发时完全执行,你们中的任何人都知道如何设置这些规则以在CI中形成验证请做分享你的知识。

1 个答案:

答案 0 :(得分:3)

您可以设置自己的验证功能类型。它有很好的记录here,但摘录如下:

<?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', 'callback_username_check');
        $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|is_unique[users.email]');

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

    public function username_check($str)
    {
        if ($str == 'test')
        {
            $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

}
?>

callback_username_check正在调用控制器中的username_check函数

回答您的最新评论

// $data is $_POST 
function my_form_validator($data)
{
    $data = 'dont worry about this';
    // you have access to $_POST here
    $field1 = $_POST['field1'];


    if($field1 OR $field2 OR $field3)
    {
        // your fields have value       
        return TRUE;
    }
    else
    {
        // your fields dont have any value
        $this->form_validation->set_message('field1', 'At least one of the 3 fields should have a value');

        return FALSE;
    }
}
相关问题