Welcome Guest, Not a member yet? Register   Sign In
Validation - check at least one field has a value?
#1

Hey all,
I have situations where a controller can accept multiple inputs, each input has the permit_empty modifier, but I need at least one input with a value to be able to do anything useful.  For example, a 'cars' controller would have search fields like 'color', 'style', 'engine type', etc. - I need to validate I have a value for at least one of those fields, doesn't matter which.  Is there any kind of validation rule that would accomplish this?  Right now I'm just checking if all of my fields are empty then throwing an exception, but it would be a lot cleaner if I could have the validator check this.
Thanks!
Reply
#2

I built a new method into BaseController to call validate() first, then if it returns true, ensure that at least one of the $rules array keys have an accompanying value, but this is kind of a narrow use case that probably won't support array validation rules very well.  If there's an official solution to this, that would probably be preferable.
Reply
#3

required_without does not help you?
https://codeigniter4.github.io/CodeIgnit...able-rules
Reply
#4

I did see required_without but didn't try it out, it didn't seem to fit what I wanted to do. I just tried it out in a controller with these rules:

Code:
$this->validate([
    'param1' => 'permit_empty|required_without[param2,param3]',
    'param2' => 'permit_empty',
    'param3' => 'permit_empty',
])

My use case is that I require any one of the params passed in my input.  'required_without' requires that my input has param1, OR has param2 AND param3.  If my input just had param2, this would fail validation since param3 wasn't populated as well.

I think this would work well if there were only two inputs I wanted to validate, but I'm not seeing a way to have this validate any one of three inputs. Maybe I'm overlooking something.

Validation rules (as I understand them) are setup to validate individual fields, sometimes in the context of other inputs.  The type of validation I'm doing isn't necessarily tied to an individual field, but rather to the entire input, so it may not be a good use case to try to fit into this validation paradigm.
Reply
#5

What about in_list[red,blue,green]
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB