CodeIgniter Forums
How validate this 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: How validate this rules (/showthread.php?tid=90916)



How validate this rules - completeorganize - 05-21-2024

I have form, if checkbox in my form (print) is checked (has value 'yes') i need validate email, if not dont validate

My rules like that


Code:
'print' => [
'label' => ' ',
'rules' => 'permit_empty|in_list[yes]',
],

'email' => [
'label' => ' ',
'rules' => 'required_with[print]|max_length[30]|valid_email'
]


When i valudate without print i got error from valid_email


RE: How validate this rules - warcooft - 05-22-2024

It seems not enough to do with rule params:

You can try this, maybe this is not the best way.  as follow:

Put that rules in your model:

PHP Code:
// Validation
    protected $validationRules = [
         'print' => [
             'label' => ' ',
             'rules' => 'permit_empty|in_list[yes]',
          ],

         'email' => [
             'label' => ' ',
             'rules' => 'required_with[print]|max_length[30]|valid_email'
          ]
     
    
]; 

then, in your controller method add exception:
        
PHP Code:
        $data  $this->request->getVar();        
        
        $rulesException 
= [];

        if (empty($data['print'])) {
            $rulesException [] = 'email';
        }

        // Checks whether the submitted data passed the validation rules.
        if (!$this->validateData($data$model->getValidationRules(['except' => $rulesException]))) {
            // The validation fails, so returns the form.
            // do something ..