codeigniter 表单验证和数组作为字段名称
我的 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');
但是在测试此复选框时,我收到了一条关于复选框的错误消息对于名称age[],我只想检查age[]不为空。
我怎样才能实现这个目标?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能像这样测试
age[]
,它是一个数组。有几种方法可以做到这一点,但您所做的require
不是其中之一。您可以使用 javascript 或通过您自己的自定义 age[] 值rel="nofollow">回调函数是一种方法。
在 CI 中使用数组的详细信息如下:
https://ellislab.com/codeigniter/user-guide/libraries/form_validation .html#arraysasfields
如果您使用 javascript 路由,则可以使用 jQuery 迭代您的复选框(使用类来链接它们)并确保其中 1 个已被检查。
You cannot test
age[]
like that, it is an array. There are a few ways to do this but what you didrequired
is not one of them.You could use javascript or by running the
age[]
value through your own custom callback function is one method.Details for using arrays in CI are here:
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#arraysasfields
If you do it the javascript route, you can use jQuery to iterate through your check boxes (use a class to link them) and just make sure that 1 of them is checked.
老问题,但对于任何努力做到这一点的人,我相信您可以通过在
age
而不是age[]
设置规则来做到这一点,即Old question but for anyone struggling to do this I believe you can do this by setting a rule on
age
rather thanage[]
, i.e.