CodeIgniter Forums
Conditional validation? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Conditional validation? (/showthread.php?tid=86870)



Conditional validation? - vinyl - 02-22-2023

I am working on a form that has a set of checkboxes. Ones one checkbox is check with value "phone" I would like to then require a set of radio buttons. 
Right now I have this: 

PHP Code:
$validation = \Config\Services::validation();
 
$request = \Config\Services::request();
 
$rules = [
  'hardware' => [
    'label'  => 'Hardware',
    'rules'  => 'required',
    'errors' => [
      'required' => 'Choose hardware',
    ],
  ], 
 ];

 
// type of hardware if phone, require type of phone
 
if ($request->getPost('hardware[0]')) {
  $rules = [
    'phone_type' => [
      'label'  => 'Phone type',
      'rules'  => 'required',
      'errors' => [
        'required' => 'Choose type of phone',
      ],
    ],
 
  ];
 }

if (! 
$this->validate$rules )) {
  return view('form', [
    'validation' => $this->validator
  
]);
 } 
This works but it overwrites my previous $rules. How can I append a rule?