I have 3 fields in my form - lets say A, B, and C. I want to set the validation rules to where if fields A and B are empty then require C. Otherwise, require A and B.
I looked up some material on this and basically I found that I can use a callback function, but I'm a little new to CodeIgniter and I can't quite figure out the syntax to write this out.
A callback is the cleanest way to handle this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class YourController extends CI_Controller {
public function save()
{
//.... Your controller method called on submit
$this->load->library('form_validation');
// Build validation rules array
$validation_rules = array(
array(
'field' => 'A',
'label' => 'Field A',
'rules' => 'trim|xss_clean'
),
array(
'field' => 'B',
'label' => 'Field B',
'rules' => 'trim|xss_clean'
),
array(
'field' => 'C',
'label' => 'Field C',
'rules' => 'trim|xss_clean|callback_required_inputs'
)
);
$this->form_validation->set_rules($validation_rules);
$valid = $this->form_validation->run();
// Handle $valid success (true) or failure (false)
}
public function required_inputs()
{
if( ! $this->input->post('A') AND ! $this->input->post('B') AND $this->input->post('C'))
{
$this->form_validation->set_message('required_inputs', 'Either A and B are required, or C.');
return FALSE;
}
return TRUE;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With