Form validation MIN or MAX on posted array fields |
Hi,
While working on my project I found that CI does not have any rules for posted field arrays for checking if the array contains a minimum or maximum allowed selection. When using min_length or max_length CI validates each value within the array, but not the array count itself. Sometimes your form will have a multi select or check boxes. And you would like too set a minimum or maximum on that field. (Please select at least 2 values OR No more than 3 selections allowed) I added two rules by extending the Form_validation class and extended the _execute method. The added methods: min_selection PHP Code: /** max_selection PHP Code: /** The extended method _execute PHP Code: /** The extended _execute method will first check if min_selection or max_selection has been set as a rule. If they have been set, the methods are executed for validation. When found, the rule is removed from the rules array so that the remaining rules can be validated as normal. Add these lines to the form_validation_lang.php as default error messages Code: $lang['form_validation_min_selection'] = 'The {field} field must contain at least {param} selections.'; That should be it. Your CI can now validate posted field arrays based on minimum or maximum selection rules Should you find any bug or problem with the code, please let me know. – Kind regards, Martin
Forgot this.
To use the rules just add it like this PHP Code: $this->form_validation->set_rules('checkboxes', 'Some checkboxes', 'required|min_selection[2]|max_selection[5]');
It is rather a specialist condition. I have never had a need for anything other than at least one of the options must be chosen, and that is easily achieved. However you method for achieving your goal was quite an interesting one. I am guessing most people would use a callback and write their own function that way.
Best wishes, Paul.
Thanks for the feedback.
We build quite a lot of forms for our customers that require this option. Reservation and survey forms need it al the time. So I came up with this and just wanted to share it. Best wishes, Martin
I am use callbacks in this case, but your way is most simple. I'll use your code to refact my project.
PHP Code: $this->form_validation->set_rules('checkboxes[]', 'checks', 'required|callback_valid')->set_message('valid', 'Max 2 options');
|
Welcome Guest, Not a member yet? Register Sign In |