我的 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>
我在我的 Controller 中设置了一个验证规则(在我看来)确保复选框已被选中,
$this->form_validation->set_rules('age[]', 'age group', 'required|trim');
然而,在测试这个时,我收到一条错误消息,显示名称为 age[] 的复选框,我只想检查 age[] 是否为空。
我怎样才能做到这一点?
最佳答案
你不能像那样测试 age[]
,它是一个数组。有几种方法可以做到这一点,但您所做的 required
不是其中之一。
您可以使用 javascript 或通过您自己的自定义运行 age[]
值 callback function是一种方法。
在 CI 中使用数组的详细信息在这里:
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#arraysasfields
如果您使用 javascript 路由,您可以使用 jQuery 遍历您的复选框(使用一个类来链接它们)并确保其中 1 个被选中。
关于php - codeigniter 表单验证和数组作为字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7727048/