php - codeigniter 表单验证和数组作为字段名称

标签 php forms codeigniter checkbox validation

我的 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/

相关文章:

javascript - 发布在 Ajax 中无法将输入保存到数据库

php - 如何在不使用 "counter"变量的情况下找出 PHP 中 foreach 构造循环的次数?

c++ - 在 Windows 窗体应用程序上检查 Tic Tac Toe 游戏的获胜者 - C++

ruby - Rails 3 如何处理常量

php - CodeIgniter - 引用 URL - 保存在数据库中

php - 有没有一种简单的方法可以从 PHP 中的 SQL 时间戳获取 Unix 时间戳?

javascript - 表单操作调用按钮

codeigniter - 将 URL 重定向到 SEO 友好 URL 时使用哪个重定向?

php - 插入查询成功但数据库出现错误?

javascript - PHP 和 JS 中 cookie 数组的最佳性能选择?