在 codeigniter 中,我对多个输入使用相同的名称(type="text"),在提交期间我想允许至少一个值,我如何验证?

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?

我的代码片段:

<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>

如果我使用以下 CI 验证:

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

然后直到填写所有字段才允许..

我想允许至少一个..我怎么能?

获取输入表单表单

$weight    = $this->input->post('weight'); //or get as your form

$weight 是一个数组,因此您可以使用 foreach 循环来验证每个元素,如下所示:

foreach($weight as $key=>$val) 
{
    $this->form_validation->set_rules("weight[".$key."]", "weight", 'required|numeric');
   // you can have one more row as per your requirement.  
}

创建您自己的验证方法:

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

并且在同一个控制器中:

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;
}

更多信息:https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods