Vahid Najafi
Vahid Najafi

Reputation: 5243

Codeigniter form validation in config depends on another input

I'm using Codeigniter form validation by config (not setting rules manually). What I need, is setting required rule depending on the other field. For example, Imagine we have the following rules:

'user' => array(
    array(
        'field' => 'user[phone]',
        'rules' => 'required'
    ),
    array(
        'field' => 'user[email]',
    ),
    array(
        'field' => 'user[foo]',
        //'rules' => 'required'
    )
),

foo input must be required based on email field.

Note: It can be done with callback function, but it makes it a bit difficult in big applications. Any idea?

Upvotes: 2

Views: 794

Answers (1)

Tpojka
Tpojka

Reputation: 7111

In your APPPATH.'config/form_validation.php' file set separated rule arrays

$config = array(
    'yes_email' => array(
        array(
            'field' => 'user[phone]',
            'rules' => 'required'
        ),
        array(
            'field' => 'user[email]',
        ),
        array(
            'field' => 'user[foo]',
            'rules' => 'required'
        )
    ),
    'no_email' => array(
        array(
            'field' => 'user[phone]',
            'rules' => 'required'
        ),
        array(
            'field' => 'user[email]',
        ),
        array(
            'field' => 'user[foo]',
        )
    ),
);

, then in controller use what ever rule set you want. In example

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

Before this check, you should determine what rule you need there with something like:

$rule = 'no_email'; // set default value

switch($this->input->post('email')) {
    case false:
        break;
    default:
        $rule = 'yes_email'; // email has been posted / needed by app etc.
}

More in docs.

Upvotes: 3

Related Questions