Search code examples
phpcodeignitercodeigniter-2codeigniter-3

in codeigniter, i am using same name for multiple inputs(type="text"), during submit i want to allow at least one value, how can i validate?


My code snippet:

<div class="col-sm-2">
    <label>Weight</label>
    <?php for($i=0;$i<4;$i++){ ?>
      <input type="text" placeholder="Weight" name="weight[]" id="weight_<?php echo $i; ?>" class="form-control weight_cls" />
    <?php } ?>
    <div class="err"><?php echo form_error('weight[]'); ?></div>
</div>

If i use following CI validation:

$this -> form_validation -> set_rules('weight[]', 'Weight', 'required|numeric');

Then it will not allow until fill all fields..

I want to allow at least one.. how can i??


Solution

  • Create your own validation method :

    $this->form_validation->set_rules('weight[]', 'Weight', 'callback_weight_check');
    

    And in the same controller :

    public function weight_check($weight)
    {
         if(count(array_filter($weight)) == 0) {
             $this->form_validation->set_message('weight_check', 'Fill at least one value');
             return false;
         }
    
         return true;
    }
    

    More infos : https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods