CodeIgniter - Captcha回调验证不起作用

时间:2014-08-01 09:54:21

标签: php codeigniter validation callback captcha

我想请一些帮助。

这是一个包含联系表单上所有验证的数组

class Contact_Form extends CI_Controller
{
    private $_validation = array(
        'fullname' => array(
            'field' => 'fullname',
            'label' => 'Fullname',
            'rules' => 'trim|required|max_length[255]'
        ),
        'email' => array(
            'field' => 'email',
            'label' => 'Email Address',
            'rules' => 'trim|required|max_length[255]|valid_email'
        ),
        'phone' => array(
            'field' => 'phone',
            'label' => 'Phone',
            'rules' => 'trim|max_length[10]|integer'
        ),
        'message' => array(
            'field' => 'message',
            'label' => 'Message',
            'rules' => 'trim|required'
        ),
        'captcha' => array(
            'field' => 'captcha',
            'label' => 'Security Code',
            'rules' => 'trim|required|callback_validate_captcha'
        )
    );

// This is the part where I validate my contact form inside a method
$this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);
        if ($this->form_validation->run() === true) {
            echo 'works!';  
        }

这是验证验证码

的回调函数
public function callback_validate_captcha($str) {
        $post_captcha = $this->input->post('captcha');
        $set_captcha = $this->session->userdata('captcha');

        if (strcmp($set_captcha, $post_captcha) !== 0) {
            $this->form_validation->set_message('validate_captcha', '%s is wrong');
            return false;
        }       
        return true;
    }

如果我在空表单上点击提交,我会收到错误,该错误表明验证码是必填字段,但如果我提交了错误的代码,则根本不会收到任何错误,这意味着回调正在进行忽略。

我试图改变我的if语句

// change this (althought i feel its more correct)
if (strcmp($set_captcha, $post_captcha) !== 0)

// to this
if ($set_captcha != $post_captcha)

但问题仍然存在。任何想法有什么不对?

1 个答案:

答案 0 :(得分:0)

你犯了一个重大错误,你必须使用函数validate_captcha而不是callback_validate_captcha。 因为回调是用于调用函数的form关键字,只需尝试和bingo