1
votes

I'd like some help please.

This is the array that holds all the validation on a contact form

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!';  
        }

This is the callback function that validates the captcha

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 i hit submit on an empty form I get the error that idicates that captcha is a required field, but if i submit a wrong code i don't get any error at all, which means that the callback is being ignored.

I tried to change my if statement

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

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

but the problem remains. Any ideas what's wrong?

1
here is one problem i can initially see, change callback_validate_captcha to validate_captcha. When you are naming the methods for your callback methods they don't need the callback_ prefix. - mic
You mean in here $this->form_validation->set_message('validate_captcha', '%s is wrong'); ?? - ltdev
no the actual method name in your controller, everything else looks okay. change public function callback_validate_captcha($str) to public function validate_captcha($str) - mic
You 're right! I forgot to remove the 'callback_' part while i was coping and pasting the name. silly mistake :) - ltdev

1 Answers

0
votes

you are making major mistake you have to make function validate_captcha instead of callback_validate_captcha. Because callback is form keyword to call a function just try and bingo