在codeigniter 3中进行自定义验证

时间:2016-07-12 13:17:03

标签: php codeigniter validation

我不喜欢codeigniter的一件事是验证逻辑在控制器内部,很容易增加和搞乱代码。为了将这个逻辑与控制器分开,我创建了一个导入form_validation library

的模型
Class BS_Validator extends CI_Model 
{ 
    protected $rules = array(); 
    protected $fields = array();

    # Get keys of fields.
    public function getStructure()
    {
        return array_keys( $this->fields );
    }

    # Validate $_POST against the rules and fields.
    public function validate()
    {
        $this->load->library('form_validation');

        foreach( $this->rules as $key => $rule )
        {
            $this->form_validation->set_rules( $key, $this->fields[$key], $rule );
        }

        return $this->form_validation->run( $this );
    }
}

对于每次验证,我都会扩展这个类:

class User_Create extends BS_Validator
{
    protected $fields = array(
        'name' => 'Nome',
        'email' => 'Email',
        'password' => 'Senha',
        'password_repeat' => 'Repetir senha'
    );

    protected $rules = array(
        'name' => 'required|min_length[3]|max_length[50]',
        'email' => 'required|min_length[8]|max_length[100]|valid_email|is_unique[users.email]',
        'password' => 'required',
        'password_repeat' => 'required|callback_password_repeat_check'
    );

    public function password_repeat_check ($password_repeat)
    {
        return true;
    }
}

除了自定义验证方法之外,一切都像魅力一样,永远不会被调用。在这种特定情况下,它总是返回(pasword_repeat_check)错误。

我应该如何识别这种方法?

1 个答案:

答案 0 :(得分:0)

无法让它以这种方式运作。

我使用的替代方法是在MY_form_validation.php文件夹上创建文件libraries,以扩展Form_validation类。

class BS_Form_validation extends CI_Form_validation
{
    protected $CI;

    function __construct($rules = array())
    {
        parent::__construct($rules);
    }

    public function password_repeat ($password_repeat)
    {
        return $_POST['password'] == $password_repeat;
    }
}

有了这个,我可以创建rules而不是callback rules,并且可以将其调用如下(不需要回调_ 前缀):

protected $rules = array(
        'name' => 'required|min_length[3]|max_length[50]',
        'email' => 'required|min_length[8]|max_length[100]|valid_email|is_unique[users.email]',
        'password' => 'required',
        'password_repeat' => 'required|password_repeat'
    );