CodeIgniter Forums
form_validation.php in config and conditional validation rules - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: form_validation.php in config and conditional validation rules (/showthread.php?tid=69921)

Pages: 1 2


RE: form_validation.php in config and conditional validation rules - Elias - 02-17-2018

(01-30-2018, 09:42 AM)webmachine Wrote: I have made a CRM in CodeIgniter that I am working on improving, and want to move all the form validation rules to a form_validation.php file in the config folder. It is working fine, but some of my rules are conditional on other form fields responses, and I don't know how to integrate those rules into the file's arrays.

Would I make a separate small array for each conditional rule, and place it as a new set of rules outside the main method validation array? Or can I make a part of the main validation array conditional?

And a good (for me) solution from my project:

PHP Code:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class 
Main_model extends CI_Model {

    private function get_rules()
    {
        return [
            [
                'field' => 'username',
                'label' => 'Name',
                'rules' => [
                    'required',
                    [
                        'username_callable',
                        [$this'username_check']
                    ],
                ],
            ],
            [
                'field' => 'useremail',
                'label' => 'Email',
                'rules' => 'required|valid_email',
            ]
        ];
    }

    public function register()
    {
        $this->form_validation->set_rules$this->get_rules() );

        if($this->form_validation->run() === FALSE)
        {
            return 'Not registered!';
        }
        else
        
{
            return 'Registered!';
        }
    }

    public function username_check($username)
    {
        if($username != 'John')
        {
            $this->form_validation->set_message('username_callable''You must be John!');
            return FALSE;
        }
        else
        
{
            return TRUE;
        }
    }