CodeIgniter Forums
CI4 equivalent of $this->form_validation->set_data($data); - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: CI4 equivalent of $this->form_validation->set_data($data); (/thread-77259.html)



CI4 equivalent of $this->form_validation->set_data($data); - mokalovesoulmate - 08-08-2020

Hello,

I need to validate a value outside of $_POST data. In CI3 I could easily manually assign data before running validation:

PHP Code:
$data = array(
        'username' => 'johndoe',
        'password' => 'mypassword',
        'passconf' => 'mypassword'
);

$this->form_validation->set_data($data); 


But it seems this feature is not exist on CI4.

How to do this?

Thanks.


RE: CI4 equivalent of $this->form_validation->set_data($data); - jreklund - 08-08-2020

Hi, you do it like this.

PHP Code:
$validation =  \Config\Services::validation();
$validation->setRules($rules$messages);
$validation->run($data); 



RE: CI4 equivalent of $this->form_validation->set_data($data); - mokalovesoulmate - 08-08-2020

(08-08-2020, 12:09 PM)jreklund Wrote: Hi, you do it like this.

PHP Code:
$validation =  \Config\Services::validation();
$validation->setRules($rules$messages);
$validation->run($data); 

It worked, thanks.

Reference: https://codeigniter4.github.io/userguide/libraries/validation.html#setting-custom-error-messages

Final code:
PHP Code:
            $data = array(
                'variable1' => $some_value,
            );

            $rules = [
                'variable1' => 'required|min_length[12]|max_length[15]',
            ];

            $messages = [
                'variable1' => [
                    'required' => 'Variable 1 required.',
                    'min_length' => 'Minimum 12 characters.',
                    'max_length' => 'Maximum 15 characters.',
                ],
            ];

            $validation = \Config\Services::validation();
            $validation->setRules($rules$messages);

            if (!$validation->run($data)) {
                
// validation failed
                $errors $validation->getErrors();
            } else {
                
// validation success