2011-10-11 60 views
4

我有一组在我的HTML复选框看起来像这样的,笨表单验证和数组作为字段名

div class="grid_7"> 
        <fieldset class="age shadow_50"> 
         <label class="legend">Age Group</label> 
          <div class="formRow checkbox"> 
    <input id="" type="checkbox" name="age[]" value="child" /> 
    <label>Child</label> 
</div> 

          <div class="formRow checkbox"> 
    <input id="" type="checkbox" name="age[]" value="30's" /> 
    <label>30s</label> 
</div> 
          <div class="formRow checkbox"> 
    <input id="" type="checkbox" name="age[]" value="60's" /> 
    <label>60's</label> 
</div> 

          <div class="formRow checkbox"> 
    <input id="" type="checkbox" name="age[]" value="teen" /> 
    <label>Teen</label> 
</div> 
          <div class="formRow checkbox"> 
    <input id="" type="checkbox" name="age[]" value="40's" /> 
    <label>40's</label> 
</div> 

          <div class="formRow checkbox"> 
    <input id="" type="checkbox" name="age[]" value="70's" /> 
    <label>70's</label> 
</div> 
          <div class="formRow checkbox"> 
    <input id="" type="checkbox" name="age[]" value="20's" /> 
    <label>20's</label> 
</div> 

          <div class="formRow checkbox"> 
    <input id="" type="checkbox" name="age[]" value="50's" /> 
    <label>50's</label> 
</div> 
        </fieldset> 
       </div> 

我已在我的控制器验证规则(在我心中)可确保复选框被选中,

$this->form_validation->set_rules('age[]', 'age group', 'required|trim'); 

当测试这个,但是我得到一个错误信息与名年龄过复选框[]我只是想检查,年龄[]是不是空的。

我该如何做到这一点?

回答

1

你不能像这样测试age[],它是一个数组。有几种方法可以做到这一点,但你做了什么required不是其中之一。

您可以使用javascript或通过运行age[]值通过自己的自定义callback function是一种方法。

细则在CI使用数组的位置:
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#arraysasfields

如果你这样做了JavaScript的路线,你可以使用jQuery通过您的复选框迭代(使用类将它们连接),只是确保其中1个被检查。

0

老问题,但任何人都努力做到这一点,我相信你可以通过设置在age的规则,而不是age[]做到这一点,即

$this->form_validation->set_rules('age', 'age group', 'fnName');