2011-10-11 59 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');