I have a form with a multi-select input field that returns an array depending on user’s selection, the user has 12 options to choose from, which means that there’s no more than 12 options to select. Also the user has the freedom to choose more than one option.
So, in the worst case the user will choose 12 options and an array will be POSTed with these options, I shouldn’t accept more than 12 options or less than 1 option.
Anyway, by looking at Codeigniter’s form validation library I didn’t find any rule for dealing with array’s length (maybe *_length works for arrays?)
Also, I did some quick researches but I couldn’t find anything useful, or even related to my problem.
The only solution I have in mind is creating a custom function that checks for array’s length
(using count(Array)) by passing the function with min and max length as a rule, this might work well, but I’m looking for a native way of doing it, Also I’m afraid of “reinventing the wheel.”
I would not seek to check the length of the posted array data, since you will then need to check that everything submitted actually existed as an option to select anyway.
So you will automatically be validating the input when you check anything selected was one you could possibly choose from (if you simply unique the array values first).
You still need a custom function though, as you need to compare the submitted values against what should have been possible to select from. Presumably these values exist in the DB somewhere, so in your custom validation routine, take the input array, unique it in case they for some reason tried to submit the same thing multiple times, then loop through all the submitted items to ensure they ALL exist as options selectable.
BTW, ‘less than 1 option’ would be the absence of a POST data for the
nameof the multi-select you’re referring to.