Validation sum of input |
hello
i want to validate sum of input array equal 100 if i post form with this value : blanc : 30 brun : 50 cuisine : 60 informatique : 70 telephonie : 80 autre : 90 if sum not equal 100, i send an error, i must have 100 html : Code: <div class="tab-cell w50prc"> PHP Code: $this->ci->form_validation->set_rules('repartition[]', 'répartitions', 'trim|callback_checkTotalRepartitionsTest[repartition]'); This works but the test is performed 6 times, which is not good PHP Code: public function checkTotalRepartitionsTest($str,$field){ thanks
What do you mean when saying "is not good"? The rule is executed for each input in that repartition array.
Website: http://avenir.ro
The test runs on each input, at the first control, I already know if the value of 100 is good or not.
But in this configuration, the script still executes the other 5 times, for an identical result. I would have liked to find a solution so that it runs only once, the other 5 being useless
One possible solution would be to add an extra field with the total sum. This may be a hidden field. Apply the callback rule to this field. The callback function adds up the numbers that were filled in in the 5 repartition[] fields. Return true if it's exactly 100, or false if it's smaller or greater than 100.
You could also fill the sum field dynamically with Javascript, or AJAX just before posting the form.
I am not sure this will help at all, but I would consider that this is your business logic and not a form_validation process. All the form_validation does is make sure you are getting the data formats you expected. After that, your business logic might demand that the submitted data adds up to 100, your business logic tested, you would then process your page however you need to after that, including returning your own error messages that are not part of the form validation routines, even though they would be shown on your form page.
For instance, your business logic might get more complicated in the future, where some accounts are allowed 150, or only 50 during a trial period. Or perhaps a temp process where anything below 100 is allowed. Whatever the reason for the 100 total, I would say this is business logic and should be done after the form_validation has checked the data are integers, of a max and min length etc. ps array_sum is a great function. I thought it might generate an error with 'hello' in the array but it just ignores it. Never used it myself but just had a play with it on phpfiddle, great function. |
Welcome Guest, Not a member yet? Register Sign In |