Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a conditional for set_rules() with form validation in CodeIgniter?

Tags:

codeigniter

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.

like image 865
jayer Avatar asked Dec 12 '22 18:12

jayer


1 Answers

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;
    }
}
like image 112
Wolf Avatar answered Jun 09 '23 07:06

Wolf